JQuery/Ajax - Load new data in page after database call using .replaceWith or .html?

StackOverflow https://stackoverflow.com/questions/11112487

  •  15-06-2021
  •  | 
  •  

سؤال

I'm curious as to how to get my AJAX/JQuery to update the page with the new database information.

Research into existing questions suggests these posts might be helpful:

jQuery AJAX calls to database work, but not in order

jQuery AJAX using fadeIn + replaceWith

Consistent with these suggestions, I have created a PHP function which processes the data sent with AJAX. On Success, I fadeOut the old HTML, and replaceWith the new HTML.

The problem is that the new data from the database is not displayed the first time the DOM element is clicked, but it DOES display the second time it is clicked. I am also getting an unwanted page refresh on the second click.

You can see a live example (for my wedding website) at: http://bucketlingerwedding.com/80s-music-reception/

If you try to vote up, it does not work the first time, and works the second time (except the page reloads).

Another concern I have is that I don't know whether cache: should be set to 'false' or simply omitted. Part of the problem may be that the new HTML I am loading with replaceWith (I have also tried .html()), has the same classes and ID's for each table row. I am curious, if I tried to replace a single row, instead of the whole table, and gave it a new ID and class name, would JQUERY/AJAX fadeIn that new row with the new info from the database?

Here is the code I am using for the AJAX (based partly on the posts above):

$(document).ready(function(){
//JQuery for the submission of a new list item.
    $('input.[class$="-arrow"]').click(function(e){
        e.preventDefault(); //put e in function.
        var ajaxurl = '<?php echo the_permalink(); ?>';
        if ($(this).hasClass('up-arrow')) {
            var arrowdirection = 'up';
            var entry = $(this).val();
        }
        else if ($(this).hasClass('down-arrow')) {
            var arrowdirection = 'down';
            var entry = $(this).val();
        }
        var rowid = '.line-items-rows' + '#' + entry;
        var data = {
            action: 'cb_lud_arrow_action',
            arrow: arrowdirection,
            entryID: entry
        };
        $.ajax ({
            cache: false,
            type: 'POST',
            url: ajaxurl,
            data: data,
            success: function(data){
                newtable = '<?php 
                $cb_table_code = plugins_url("list-up-down/table-up-down.php", _FILE_);
                include_once "table-up-down.php";
                echo $cb_lud_new_output;
                ?>';
                $('#cb_lud_table').fadeOut('fast', function(){
                    $(this).replaceWith(newtable).hide();
                    newtable.fadeIn('fast');
                });
                }
        });
});
});

NOTE: I have confirmed that the data posted with AJAX indeed updates the database tables, so the .php file and the ajax POST method are at least working correctly.

What I basically need is for the chronology of events to be:

  1. A user votes up (clicks) a line in the table.
  2. Data is sent to the MySQL database adding a vote in the correct column.
  3. On success, a function determines the new value from the database and generates new html.
  4. The old data fades out, the new data fades in.
  5. Everyone is happy.

It doesn't much matter to me if this is more of a JQuery solution (like putting the effects in the right order, or using a .delay() function), or more of an AJAX solution, where I setup callback functions based on the successful posting of data, or something having to do with the cache. Just want it to work. Please help.

هل كانت مفيدة؟

المحلول

Use a browser console to look at errors thrown. newtable is only a string so you can't use it as a jQuery object to call jQuery methods with. This is throwing errors in console and makes it easy to zero in on in your code.

Look in your source view of what the following outputs:

   newtable = '<?php 
            $cb_table_code = plugins_url("list-up-down/table-up-down.php", _FILE_);
            include_once "table-up-down.php";
            echo $cb_lud_new_output;
            ?>';

You likely don't need any of that string which is a complete rebuild of the table in html string, but since the whole page is also being returned in html it is complete duplication and you could simply grab the html version itself and remove the above completely.

Change to:

     success: function(data){
           /* convert whole page returned to jquery and get inner html of the table*/
            var newRows=$(data).find('#cb_lud_table').html() 
            $('#cb_lud_table').fadeOut('fast', function(){
                 /* insert new rows*/
                $(this).html(newRows).fadeIn('fast');

            });
            }

Once you get that working, you may also need to revisit how your click handlers are attached ( I haven't looked). Removing the old html also removes any events attached. Using on() delegated to the table, which will now be a permaennt asset, will compensate for changing out the html

نصائح أخرى

You have used the fadeIn function on the variable. So it throws an error newtable.fadeIn is not a function.You can not use the fadeIn function on the variable. Give the id or class name to the fadeIn function.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top