How can I use jQuery to run MySQL queries?

You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.

http://api.jquery.com/jQuery.ajax/

HTML

<input type='button' id='btnVote' value='Vote' />

Javascript

This code will be excuted when user clicks on the button with the id “btnVote”. The below script is making use of the “ajax” function written in the jquery library.It will send a request to the page mentioned as the value of “url” property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called “answer”.

 $("#btnVote").click(function(){     
    $.ajax({
            url: "ajaxserverpage.aspx?answer=5",
            success: function(data){
                alert(data)
             }
          });

  });

and in your aspx page, you can read the querystring (in this example, answer=5) and build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like “Vote captured” or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.

Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc…

EDIT : As per your comment,

jQuery support post also. Here is the format

 $.post(url, function(data) {
        alert("Do whatever you want if the call completed successfully")
 );

which is equivalent to

 $.ajax({
        type: 'POST',
        url: url,           
        success: function(data)
                  {
                    alert("Do whatever you want if the call completed successfully")
                  }           
       });

This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy

Leave a Comment