PHP and Ajax using foreach loop in the callback and return array

10,547

Solution 1

What if you try something like this:

$id = $_GET['id'];

$data = file_get_contents('__url');

parse_str($data);

$array = explode(',', $url_encoded_fmt_stream_map);

$final_arr = array();
foreach($array as $item) {
    parse_str($item);
    array_push($final_arr , $url);
}

$jsonp = json_encode($final_arr);

if(isset($_GET['callback'])){
    header("Content-Type: application/json");
    echo $_GET['callback'] . '(' . $jsonp . ')';
}else{
    echo $jsonp;
}

and your ajax:

$.ajax({
    url:"file.php",
    dataType: 'jsonp',
    data: {id: id},
    success:function(response){
        var obj = JSON.parse(response);
        $.each(obj, function(key,val){
             console.log(key);
             console.log(val); //depending on your data, you might call val.url or whatever you may have
        });
        $('body').append(response);
    }
});

Solution 2

It only returns 1 URL because it only returns the first one. You should encode your entire array and loop in the success function like so:

PHP:

$id = $_GET['id'];
$data = file_get_contents('__url');
parse_str($data);
$array = explode(',', $url_encoded_fmt_stream_map);
echo json_encode($array);

JS:

$.ajax({
    url:"file.php",
    dataType: 'jsonp',
    data: {id: id},
    success:function(response){
        var res = JSON.parse(res);
        $.each(res, function(key, index){
           $('body').append(index);
        });
    }
});
Share:
10,547
Amr SubZero
Author by

Amr SubZero

Eat, Code, Sleep, Repeat.

Updated on June 14, 2022

Comments

  • Amr SubZero
    Amr SubZero almost 2 years

    I'm trying to loop through the Callback from PHP result.

    But I can't or I don't know how to return an array as a Callback

    This is my PHP code :

    $id = $_GET['id'];
    
    $data = file_get_contents('__url');
    
    parse_str($data);
    
    $array = explode(',', $url_encoded_fmt_stream_map);
    
    foreach($array as $item) {
        parse_str($item);
        echo $_GET['callback']."(".json_encode($url).");"; // it should return an array at least 3 urls
    }
    

    And this is my Jquery code :

    $.ajax({
        url:"file.php",
        dataType: 'jsonp',
        data: {id: id},
        success:function(response){
            $('body').append(response);
        }
    });
    

    It gives me one result only but it should return an array, it's working like I did not use foreach loop in the php code.

    I tested the PHP code without Ajax Request and it returned an array of urls, but if I used the ajax callback it's returning one url only.

  • Amr SubZero
    Amr SubZero about 9 years
    Thanks for the reply, but first i'm getting an error parsing "parsererror - Parsing JSON Request failed" in the ajax request, second if it should work how can i use the &.each the right way to get every single url and use it whatever i want?
  • Daan
    Daan about 9 years
    Try to check if the JSON is valid at jsonlint.com. For your second question create an array variable and while looping put those url's in the array, so you can use them wherever you want.
  • Amr SubZero
    Amr SubZero about 9 years
    at jsonlint.com it returned an array of what i want, but the problem is when i use the ajax request i get "parsererror" and the request fail. is this happening because i'm using "jsonp" not just "json" ? i think 100% this is cuz i'm using jsonP, and i'm using it cuz the ajax reuqest goes cross domains.
  • Amr SubZero
    Amr SubZero about 9 years
    That's what i'm talking about! .. Now, it returned a list of urls but what if i want to use every url alone? .. btw you're genius :)
  • Andreas Louv
    Andreas Louv about 9 years
    Also note that JSONP is for intented for CrossSiteRequests... file.php , in your case you should be able to simply use dataType: 'json'
  • CodeGodie
    CodeGodie about 9 years
    :) you taught me something too. I wasnt aware of how this worked initially. if you now have the list of urls on your ajax result, you can do var obj = JSON.parse(result); then iterate over that object... is that what you meant?
  • Amr SubZero
    Amr SubZero about 9 years
    Good, that's what i meant but the problem that i don't know how to use jquery $.each correctly to loop through the var obj, tried but failed! if i did that you'll have an accept to your answer immediatly!
  • Amr SubZero
    Amr SubZero about 9 years
    The Thanks word isn't enough to say :) i really appreciate your help <3 thanks in advance!
  • Amr SubZero
    Amr SubZero about 9 years
    @null Yes sir, i replaced the file url with a placeholder fake 'file.php' but it's originaly a url not just a file.
  • Andreas Louv
    Andreas Louv about 9 years
    @CodeGodie Note that when callback is set the content type should be text/javascript and when not set it should be application/json