Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery ajax response data

Tags:

jquery

I am using ajax post and am receiving data in the form of html. I need to split up the data and place pieces of the data all over the page. I built my response data to be something like <p id='greeting'> Hello there and Welcome </p> <p id='something'>First timer visiting our site eh'</p> It is a little more complicated and dynamic but I can figure it out if get this question answered. Thanks

$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
            success:function(data){
                    //Need to split data here
            }
        });
like image 505
Theopile Avatar asked Jun 13 '10 04:06

Theopile


People also ask

How we can send data to server using AJAX?

ajax({ type: "POST", url: "your url with method that accpects the data", dataType: "json", data: { o: objectDataString }, success: function (data) { alert('Success'); }, error: function () { alert('Error'); } }); And your method can have only one parameter of string type.


1 Answers

Update: Just realized you should probably do this:

success:function(data) {
    data = $('<div/>').append(data);
    $('#greeting',data).appendTo('#one')
    $('#something',data).appendTo('#two')
}

As you cant use .find properly since it isnt a child but if you append it to an empty node you can. The other alternative would be using .filter

$.ajax({
            type:'POST',
            url: 'confirm.php',
            data: "really=yes&sure=yes",
            success:function(data){
                    $('#greeting',data).appendTo('#one')
                    $('#something',data).appendTo('#two')
            }
        });

You can extract from data and append where you want to. You can also do something like return JSON instead, and instead of extracting html from html just access the html from an object.

$(data.greeting).appendTo('#one')
$(data.something).appendTo('#two')

The response would have to be like:

({ 'greeting':'html', 'something' :'other html' })
like image 85
meder omuraliev Avatar answered Sep 20 '22 13:09

meder omuraliev