-2

So,I send an array of inputs:

<input type="text" placeholder="Question" name="question[]"  value="" />
<input type="text" placeholder="Question" name="question[]"  value="" />

with this Jquery code:

    $.post("function.php",{Question:$("[name^='question']").serialize()},function(data){
    $("#construct").append(data);
    alert('done');
});

but when I try to echo the variables of array it prints incorrect PHP(function.php):

$Question=htmlentities($_POST['Question'],ENT_QUOTES,"UTF-8");
echo $Question[0]."<br>";
echo $Question[1]."<br>";

Now imagine that we enter "Hello" and "Bye" in the input So it should return "Hello" and "Bye" but it returns "q" and "u" instead.

The var_dump out put is:

string(39) "question%5B%5D=Hello&question%5B%5D=Bye"

Edit 1

if I use .serialize() I always get "q" and "u" but if I use .val() I get the first and second letter of each word

Edit 2

I even tried the PHP code without htmlentities() but the result is the same as before.

3
  • Show the output of var_dump(($_POST['Question']); in your question Commented Sep 6, 2015 at 14:51
  • @JohnConde I edited my post with var_dump output Commented Sep 6, 2015 at 14:55
  • Why am I getting down-vote????? Commented Sep 6, 2015 at 15:57

1 Answer 1

1

You serialized your input in JavaScript so the input coming in PHP is a string, not an array. So you need to decode it into an array. Using JSON is a good approach.

EXAMPLE for the lazy:

JavaScript

var normalArray = $('#FormID').serializeArray();
var jsonArray = JSON.stringify(normalArray);
$.post("function.php",{
  data: jsonArray
});

PHP

$normalArray = json_decode($_POST['data'], true);

This example is not tested, but it should work in general.

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

8 Comments

So,What can I use instead of .serialize()??
use JSON.stringify( my_array ) in javascript my friend. And in PHP you do json_decode($_POST['question'], true). Here: stackoverflow.com/questions/6937144/… php.net/manual/en/function.json-decode.php
So you stringify your data in JavaScript to Json, send it to PHP, decode the Json into an array, go mark P. jensen's anwser as a good anwser. And he saw that everything was well.
Dude, don't be lazy. If you don't learn it by researching and writing it yourself, you will never remember it. Use the links I gave you.
Can I use JSON.stringify() in Jquery.post??
|

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.