简体   繁体   中英

How to refresh a page or div with jquery in order to reveal new data

I've got some jquery that submits a form for me. It works just fine. The only major problem is how simple it is.

The form submits the info to the database using my php script without refreshing the page, but the page isn't updated in any way to show the new data. What are some good ways to update the page or div so my new data is displayed after submitting the form. Below is my code

$(function() {
    $('#form').submit(function(e) {

        var data = $(this).serialize();

        // Stop the form actually posting
        e.preventDefault();

        // Send the request
        $.ajax({
            type: "POST",
            url: "submit.php",
            data: data,
            cache: false,
            success: function(html){
                $('textarea#joke').val('');
            }
        });
    });
});

You are very close, just use html() method or text() depend on your needs, for your example I think text is better, since you want put text into textarea

success: function(html){
                $('textarea#joke').text(html);
            }

but if you want put some html into custom div do

success: function(html){
                    $('#custom-div').html(html);
                }

Suppose from the submit.php, you are returning some value as status = true if form submitted suceessfully else status = false

then in your ajax code, you can use it as

success: function(html){
  if(html.status == true)
    $('textarea#joke').html('Form submitted succcessfully');
  else
    $('textarea#joke').html('ERROR!');
}

OR

success: function(html){
    $('textarea#joke').val(html.status);
}

This would update the div content of $('textarea#joke')

Hope this would help you.

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM