Hub
Hub

Reputation: 3

How to slice array passed by php/ ajax in jquery

I have got a page where visitors can use a dropdown menu to get info on a person.

After the change-call, jquery sends the ID of the person via ajax to a php-script, that pulls the data out of a database.

Because the data should be used in three different div's on the requesting page, the data is sent back as an (php) array.

And now I need your help. How can I split the array ( it has three parts ) into three javascript parts, that can be send to the specific divs (so, div1, div2 and div3)?

This is the code I have:

 $('#contentz').change(function(){
    var Value = $(this).val();  
    $.ajax({
        type: 'post',
        url: '/ajax.php',
        dataType: 'html',
        data: {action: Value},
        success:function( data){ 
    // I need to slice the array here           
            $("#veld1").html( data ); // result 1
            $("#veld2").html( data ); // result 2
            $("#veld3").html( data ); // result 3
    //alert(data); 
        }, 
        error:function (xhr, ajaxOptions, thrownError){
            //On error, we alert user
            alert(thrownError);
        }, 
        complete: function(){
            //alert('update success'); 
        }
    });
});


#contentz is the select/ dropdown.
#veld1, #veld2 and #veld3 are the divs that display the result.

Upvotes: 0

Views: 1072

Answers (3)

Lekhulal Mathalipara
Lekhulal Mathalipara

Reputation: 57

var data = array("david","belly","Jay");
$("#veld1").html( data[0] ); 
$("#veld2").html( data[1] );
$("#veld3").html( data[2] ); 

Upvotes: 0

Erik
Erik

Reputation: 123

The way I would go about this is by outputing the data in JSON format. You can have HTML in JSON but you have to respect certain things (notably escaping certain chars). Here is a link to a quick article that explains what must be done to use html in JSON: http://www.thorntech.com/2012/07/4-things-you-must-do-when-putting-html-in-json/

Upvotes: 0

Runcorn
Runcorn

Reputation: 5224

One of the easiest way to return array to AJAX is encoding it as JSON ,

$array = array("firstDivValue","secondValue","thirdDivValue");
echo json_encode($array);

And accessing it in AJAX success via ,

$.ajax({
        .......
        //Set it as JSON as we are now returning it
        dataType: 'json',
        .........
        success : function(data){

                $.each(data,function(i,value){
                    //Get value here
                    alert(value);
                });
         }

Upvotes: 1

Related Questions