简体   繁体   中英

Send array with Ajax to PHP script and Implode

This is my Ajax POST request:

function getRelated() {
    var elements = (document.getElementsByClassName('escashare'));
    var query = [];
    for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));

    $.ajax({
        type: "POST",
        url: baseUrl+"/requests/get_related.php",
        data: "query="+query+'&_token='+_token, 
        cache: false,

        success: function(html){
            $('#main-content').append(html);
        }
    });
}

So basically I POST an array of int numbers like:

["326", "311", "312", "313", "314", "316", "317", "318", "319", "15", "9", "87"]

When in my PHP I implode the query array it gives me NULL but why?

$newQuery = implode(',', $QueryFromPost);
var_dump($newQuery); //NULL

EDIT

I need to use it for:

$query = $this->db->query(sprintf("SELECT * FROM `posts` WHERE `id` IN ('%s')", $newQuery));

while($result = $query->fetch_assoc()) {
    $rows[] = $result;
}

if(!empty($rows)) {
    foreach($rows as $row) {
        $output .= '<div class="stage">'.$row['id'].'</div>';
    }
}

return $output;
    function getRelated() {
      var elements = (document.getElementsByClassName('escashare'));
      var query = [];
      for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
   // Right here you can implode the array like this :
    query = query.join();// this is now a string containing your data
    // you can then pass it in your query string 

    var jsonString = JSON.stringify(query);

    $.ajax({
    type: "POST",
    url: baseUrl+"/requests/get_related.php",
    data: {data : jsonString,token: token}, 
    success: function(html){
        $('#main-content').append(html);
    }
   });
  }

In your server side code , you will use explode and json_decode function to extract your data back from the query string .

$data = explode(",", json_decode(stripslashes($_POST['data']));
foreach($data as $d){
    echo $d;
 }
 $token = json_decode(stripslashes($_POST['token']));

EDIT Take a look at this post , it will be useful.

Hope it helps.

First in my JS function I forgot to:

query.join(',');

Next in my PHP I forgot to remove single quotes from my MYSQL query and also I don't need to use implode at all.

So here is what I did:

JS function:

function getRelated() {
    var elements = (document.getElementsByClassName('escashare'));
    var query = [];
    for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
    query = query.join(',');

    $.ajax({
        type: "POST",
        url: baseUrl+"/requests/get_related.php",
        data: "query="+query+'&_token='+_token, 
        cache: false,

        success: function(html){
            $('#main-content').append(html);
        }
    });
}

PHP function:

function getRelated($get_query) {

    $query = $this->db->query(sprintf("SELECT * FROM `posts` WHERE `id` IN (%s)", $this->db->real_escape_string($get_query)));

    while($result = $query->fetch_assoc()) {
        $rows[] = $result;
    }

    if(!empty($rows)) {
        foreach($rows as $row) {
            $output .= '<div class="stage">'.$row['id'].'</div>';
        }
    }

    return $output;
}

Credits to Ayush !

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