0

Alright so I am sending some data from PHP to Ajax (works perfectly) using Json but my problem comes in why I want to split that response.

How do I use for example alert every element?

$.ajax({        
            url:"myHandler.php",  
            type:"POST",  
            data:{function:"rxz", xLast:xx, yLast:yy},
            dataType:'json',
            success:function(data){
                alert(data); //How do I alert EVERY single data element on its own?
            },
            error:function(data) { console.log(data); }
        });

The stuff from PHP is sent like this

print json_encode(array($json_array,$from,$to));

It basically sends an array & contains From and To inside of it

2
  • did you used each loop for this? Commented Nov 24, 2016 at 1:51
  • I used array_push for the $json_array if you mean that (and yeah it was inside a loop). Commented Nov 24, 2016 at 1:51

3 Answers 3

1

Why don't you restructure your PHP to return a proper array. Something like this would be easy to handle:

print json_encode([
    'data' => $json_array,
    'from => $from,
    'to' => $to
]);

Which you can then iterate through within your jQuery:

jQuery.each(data.data, function(i, element) {
    alert(element);
});

You could even use "proper" practice and return status codes within your json ([....'status' => true/false ....]) which you can then display end results with properly.

Sign up to request clarification or add additional context in comments.

2 Comments

Well okay I tried that but nothing comes out. Alert is not being show
@TomislavNikolic have you checked your console for any errors?
1

You can use each loop for showing alert for every single element of json result

success: function(data){
       $.each(data, function(index, value){
              alert(value);
       });
}

Comments

0

Vanilla Javascript:

for (var i=0; i < data.length; i++)
   alert(data);

Now here's the tricky part. If all the elements in data are scalar, you should be fine, but if any of the elements are Arrays or Objects, then you will get [Object] in your alert. So you'd better format them right according to your expectation of result, or use JSON.stringify(element) function to convert that object into its string representation. This will do:

for (var i=0; i < data.length; i++)
   alert(JSON.stringify(data));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.