1

I have the following in my js script :

    cats = []; cats.push(cat1); cats.push(cat2);
    $.post( URL+"/edit-article.php", { id: artId, title: "PZujF0 wxKLCW", content: "ILEn3o oU9Ft6oU5", author: author, cat_id: cats } ).done(function( data2 ) {......}

cat1 and cat2 are some random generated integers, so i send to my php script an array of integers. How do i retrieve them inside my php script ? Currently i have something like this:

$cat_id=array();
$cat_id=array_map('intval',explode(',',$_POST['cat_id']));

but my code assumes that the sent array from js is the equivalent of the following :

<form action='edit-article.php' method='post'>
    <input type='hidden' name='cat_id' value='1,2'>
</form>

From the code i posted in js it's obvious that there are only 2 integers so i could probably make something like :

$cat_id=$_POST['cat_id'];
$id1=(int)$cat_id[0];
$id2=(int)$cat_id[1];

But how can i correctly parse the array in PHP for any number of elements and make sure i am left with an array of ints ?

LE: The problem i have is understanding how JS sends the data to my php script, in order to correctly extract the data. As i gather, $POST values are always retrieved as strings(is it valid for values sent from JS or just forms and stuff?), but is my cat_id array an array of strings like {'1','2','3'} or is it a string like '1,2,3' ?

1
  • use a for loop to get all the items Commented Mar 29, 2014 at 11:23

1 Answer 1

1

Currently you're sending an array, so there's no need to explode:

$cat_id = array_map('intval', $_POST['cat_id']);

Alternatively, you can create the comma separated list on the JavaScript side:

cats = cats.join();
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is what i wasn't so sure of, if i needed the explode or not, thank you :)

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.