Hello
Is it possible to use SQL queries in a JS file?

Example I have the following code, and would like for each input[type='text'] encountered, to save its value to a sql table in a column:

jQuery("input[type='text']").blur(function(){
      var id = jQuery(this).attr('id');
      var inputVal = jQuery(this).val();      
      });

Recommended Answers

All 5 Replies

No. You'll need something as an intermediairy between your client Javascript and your database server.

If you means to directly made the connection from jquery to database, then from my understanding, it cannot be done or not encaurage to be done. As jquery script is a client based scripting, so it is too risky to connect using jquery.
However, we can always using a ajax to call for a class to connect/update/insert/delete to/from the database. Here is a link to help you if you are new to ajax: http://api.jquery.com/jquery.ajax/

Member Avatar for diafol

Further to the info posted already, all javascript can be viewed by the usere, so placing SQL queries there is a bad idea. You don't want anybody to see your schema. User input should also have to be sanitized. Imagine the following:

var sql = "SELECT user, avatar FROM users";
$.get(url,{sql:sql},...);

The user could easily change the sql var "DELETE FROM users", or something to pull sensitive data.

You can use jQuery to extract info from local storage / DBs though, but this is of limited use.

Apologies if you're aware of the following already...

However, passing data input to a query on the server is what we often do via Ajax. Passing data via Ajax is pretty much the same as submitting a form. All transported input should be validated and sanitized (server side). The main difference comes from what to do with the returned data (if any). A normal form submission, would probably just pass the data data to a new page in a variable, which can then be used 'as usual'. Ajax returns data as a string in various guises (json, xml, html etc). So for this to happen, the data needs to be echoed rather than returned. You can add protection to Ajax, just as you would a form with CSRF tokens.

$(function(){
    // Bind a click event to your anchor with id `updateSal`
    $("#updateSal").click(function(){
        // get your employeeID
        var empID = "32"; 
        // issue an AJAX request with HTTP post to your server side page. 
        //Here I used an aspx page in which the update login is written
        $.post("test.aspx", { EmpID: empID},
            function(data){
                // callack function gets executed
                alert("Return data" + data);
        });

        // to prevent the default action
        return false;
    });
});

Do u mean click on some button and trigger JS to store all value into db?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.