tags:

views:

249

answers:

3

Hi guys,

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();
    }
});
A: 

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');
}
Codler
A: 

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.)

George Marian
A: 

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.

JKS
What would be the point of sending it as XML instead of HTML? XML is NOT an efficient data exchange format. (It probably would be a bit less data then the HTML necessary to render the list.) Yes, JSON is a good way to reduce the bandwidth usage. Which is better depends on what you're doing. If you have a lot of JavaScript, I'd lean towards reducing the amount of work being done in JavaScript.
George Marian
I prefer JSON over XML, because I like the syntax more and it's easier to use with JS — but really that's just preference. In terms of performance, if you save all of your HTML client side (especially as document fragments, as in http://ejohn.org/apps/workshop/adv-talk/#6), you can have, for instance, just a single data row template instead of transferring the same HTML 50 or a 100 times over. You end up inserting the same nodes anyway with straight HTML, so ultimately the the bandwidth savings have a much bigger effect than limiting your use of JS.
JKS
But you're right that if you're just sending very simple HTML, it won't make much difference. In the real world though, I was building an app where each row had embedded tables — and that extra markup alone was worth the effort to switch to JSON. We saw requests go from ~120KB for 50 rows down to ~40KB.
JKS
hmmm i see what you mean, would i need to encode my echo response in json in mt process.php? umm then set the input type to json?
s2xi
hmmm, what can be an example for data to be outputted as json? in my php page i have the table being buiild with a while($row = sql query) then populate <td> with the $row[] info I need. how would i output that data with json then use it to populate it in my javascript html markup?
s2xi
I think HTML will work fine for your purposes, but jQuery's $.getJSON() and PHP's json_encode() work perfectly together. I'll add an example to my answer.
JKS
cool! thanks for your help
s2xi
@JKS I must admit, I was being a bit lazy and trying to keep it simple.
George Marian
heh, i couldn't tell ;) hey, how would the $.ajax() be applied into your example snippet? you got me scratching my head over that haha
s2xi
@George as I probably should have done! But @s2xi, glad I could help.
JKS
From the API docs for $.getJSON (http://api.jquery.com/jQuery.getJSON/):"This is a shorthand Ajax function, which is equivalent to:$.ajax({ url: url, dataType: 'json', data: data, success: callback});" API docs are your friend!
JKS
oh! lol, yes I see what you mean. So I think I added thecode in successfully to some degree. My process.php returns a 500 Internal Error. this is what I have in process.php $_val = $_POST['recent_val-seller']; $sell_new_val = "UPDATE `settings` SET `seller_display_limit` = {$_val} WHERE `user_id` = {$_SESSION['user_id']}"; $result = mysql_query($sell_new_val) or die(mysql_error()); $json = array('rows' => array()); while ($row = mysql_fetch_assoc($result))) { $json['rows'][] = $row; } echo json_encode($json);
s2xi
This answer is verging on quite a few other questions, but you're forgetting to grab the new contact rows after you update `seller_display_limit`. You want something like:$result = "'SELECT * FROM contacts WHERE id = {$_SESSION['user_id']} ORDER BY name ASC LIMIT {$_val}";You could even set this up to use a LIMIT offset, so you only fetch exactly the rows you need (say, 5 through 10).
JKS