1

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;
NineCattoRules
  • 2,253
  • 6
  • 39
  • 84
  • `var_dump($QueryFromPost)` – u_mulder Mar 12 '17 at 10:31
  • Convert your `query` object to a string and then in your PHP try echoing `$QueryFromPost` and check what you get. – Ayush Mar 12 '17 at 10:34
  • @u_mulder that gives me `[Object object]` – NineCattoRules Mar 12 '17 at 10:36
  • @Ayush I tried `query.toString();` this is the POST `query:326,311,312,313,314,316,317,318,319,15,9,87` and the Response is a `string(43) "326,311,312,313,314,316,317,318,319,15,9,87"` – NineCattoRules Mar 12 '17 at 10:39
  • @NineCattoRules post var_dump from php, [Object object] looks like js debug – bxN5 Mar 12 '17 at 10:45
  • 1
    @NineCattoRules use `query.join(',')` to convert it into a single string. – Ayush Mar 12 '17 at 10:48
  • @Ayush I'm losing my religion...it's the same, `var_dump($QueryFromPost);` gives me a `string(43) "326,311,...` and `var_dump($newQuery );` gives me `NULL` – NineCattoRules Mar 12 '17 at 11:00
  • @NineCattoRules Why are you imploding the `$QueryFromPost`. It is already a `,` separated string. `implode` works on arrays. Do you want to `explode` it? Separate it into different values?? – Ayush Mar 12 '17 at 11:24
  • @Ayush that's true but I need to use inside WHERE IN clause of MYSQL, question edited. If I use the `$QueryFromPost` it outputs only the first element of my string. – NineCattoRules Mar 12 '17 at 11:34
  • 2
    @NineCattoRules You need to remove quotes from the string to use it into mysql query. The quotes maybe conflicting with your query. Try to form a proper query and then run it in your mysql code to check it's validity. – Ayush Mar 12 '17 at 11:38
  • I don't see you grabbing the posted variables or $QueryFromPost with $_POST anywhere in your code – user3526204 Mar 12 '17 at 15:20

2 Answers2

0
    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.

Community
  • 1
  • 1
kourouma_coder
  • 1,078
  • 2
  • 13
  • 24
0

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!

NineCattoRules
  • 2,253
  • 6
  • 39
  • 84