Tutorial :jQuery/Ajax SQL live update via PHP help



Question:

I have a table that outputs all my contacts via a while loop from my database.

my syntax is like this:

SELECT * FROM contacts WHERE id = $_SESSION['user_id'] ORDER BY name ASC LIMIT 5  

that pulls out all my data and only gives me 5 results.

Now my goal is to have a little button that opens up a model box with jquery (this I can manage on my own) with a form asking the user to input a number then that number will be sent via post or get to $PHP_SELF and update a local variable with the number the user inputed, then that variable will be used to update the database to increase or decrease the LIMIT value.

I have looked all over the web (with google) to look for submitting a form using AJAX but all the examples i've found don't work for me.

When the user submits the number and the sql query is executed and updated for the outputed table to dynamically update according to the new LIMIT value all without ever refreshing the page to the user.

my jquery code is:

(document).ready(function(){     $("form#form").submit(function() {     // we want to store the values from the form input box, then send via ajax below        var val = $('input[name=new_value]').attr('value');        $.ajax({            type: "post",            url: "process.php",            data: "val="+ val,            cache: false,            success: function(){               $('form#form').hide(function(){$('.success').fadeIn();});            }        });        return false;     });  });    $(document).ready(function(){ $("form#form").submit(function() {     // we want to store the values from the form input box, then send via ajax below     var val =    $('input[name=new_value]').attr('value');     $.ajax({ type: "post", url: "process.php", data: "val="+ val, cache: false, success:        function(){        $('form#form').hide(function(){$('.success').fadeIn();});     } }); return false; }); });  

then my php code is:

$new_val = $_POST['new_val'];  $_val = "UPDATE `settings` SET `display_limit` = {$new_val} WHERE `user_id` = {$_SESSION['user_id']}";  mysql_query($_val) or die(mysql_error());  

and my form is simple:

any suggestions? I haven't come to how to have my outputed table dynamically update yet so if anyone can point me in the right direction or provide some help that would be awesome.

thanks

EDIT:

Here is an updated jquery script I was working on, I'm able to submit the form successfully! but my only problem is that I can't see the changes until the page is refreshed with defeats the purpose of the AJAX usage... sigh

how can I now have my #results div updated and refreshed with the form submission content?

$(document).ready(function() {       var options = {          url: 'process.php',          type: 'post',          //dataType:  'json',          target: '#last_five_sellers',          success: success      };        // bind to the form's submit event       $('#form').submit(function() {           // inside event callbacks 'this' is the DOM element so we first           // wrap it in a jQuery object and then invoke ajaxSubmit           $(this).ajaxSubmit(options);           // !!! Important !!!           // always return false to prevent standard browser submit and page navigation           return false;       });      function success(responseText, $form) {          $("form#form").hide();          $(".success").fadeIn();      }  });  


Solution:1

In your php code where you do the update, You could echo your contacts in html-format. That would then return to your success function in jquery.

success: function(){      $('form#form').hide(function(){$('.success').fadeIn();});  }  

The function have a parameter data, which is the html-format you echoed in php. Example

success: function(data){      $('form#form').hide(function(){$('.success').fadeIn();});      $(data).appendTo('#result');  }  


Solution:2

You need to understand the flow of a request. Once the php script runs, that is it, it is done. If you plan on submitting back to that same page, it'll be a new request and a new execution of that script. Now, you could add a special case to that script to return the necessary data to your jQuery code, but that's messy IMO. I would rather have a separate script to handle that functionality. This can be looked at as a web service.

So, when a you go to that page in a browser, it will intially display 5 contacts (or w/e the default you have in the LIMIT clause). When you click the icon to display more contacts, you employ jQuery to submit a GET request to that 'web service' page (it really should be GET, since you're retrieving data, not submitting new data). This would then be a list of contacts that you use to update the display on the page, using jQuery/JavaScript.

As noted by Codler, the output from that 'web service' can be HTML which you simply use to replace the existing HTML which displays the contacts. (This would be the preferred way. You almost always want do as much on the server as you reasonably can.)


Solution:3

It looks like your jQuery code is duplicated â€" there's no need to bind the form's submit event twice. Additionally, the first jQuery block is missing the opening dollar-sign ("$"). And as far as I know, .hide() does not support passing a callback through the first parameter. In the jQuery API documentation, it's written as .hide( duration, [ callback ] ).

I would write:

$(function(){     $("form#form").submit(function(){     // we want to store the values from the form input box, then send via ajax below        $.ajax({            type: "post",            url: "process.php",            data: "val=" + $("input[name=new_value]").val(),            cache: false,            success: function(){               $("form#form").hide();               $('.success').fadeIn();            }        });        return false;     });  });  

Now, if you want to update your results table dynamically, the simplest way is just to replace the entire thing with the updated HTML. So for instance, if you modified your PHP script (process.php) so that, after updating display_limit, it outputted the new results table, you could then write something like (assuming your results table is table#results):

$(function(){     $("form#form").submit(function(){     // we want to store the values from the form input box, then send via ajax below        $.ajax({            type: "post",            url: "process.php",            data: "val=" + $("input[name=new_value]").val(),            cache: false,            success: function(data){               $("form#form").hide();               $(".success").fadeIn();               $("#results").replaceWith(data);            }        });        return false;     });  });  

You just have to make sure your script only outputs HTML.

Contrary to what George answers above, HTML will definitely work for this purpose, but I think the ideal method is to send purely the data alone (minus structure/presentation) in either JSON or XML format, and then use JavaScript to build the HTML; you can save a lot of bandwidth this way, and ultimately build a much more responsive application.

EDIT

Here's a mini JSON-based example.

JavaScript:

$(function(){      $("#form").submit(function(){          var val = $("input[name=new_value]").val();          $.getJSON("process.php?val=" + val, function(data){              $("#results").empty();              $(data.rows).each(function(){                  $("#results").append('<tr><td>' + this.column_a + '</td><td>' + this.columbn_b + '</td></tr>');              });          });          return false;      });  });  

PHP (process.php):

[assuming you already have a result/rows called $result]  $json = array('rows' => array());  while ($row = mysql_fetch_assoc($result)) {      $json['rows'][] = $row;  }  echo json_encode($json);  

Now, granted, I haven't tested this code at all, but it should give you the gist of it.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »