I have array in my JS and I have to parse it to PHP:
var transfer_data = {
cl_name : $("#free_1_1_title").val(),
contact_name : $("#free_1_1_name").val(),
contact_lastname : $("#free_1_1_lastname").val(),
contact_email : $("#free_1_1_email_1").val(),
cl_alley : $("#free_1_1_select_1").val(),
cl_services : $("#free_1_1_select_2").val(),
cl_tags : {
1 : $("classified_tag_1").val(),
2 : $("classified_tag_2").val(),
3 : $("classified_tag_3").val(),
4 : $("classified_tag_4").val(),
5 : $("classified_tag_5").val()
}
};
and transfering:
$.ajax({
url: "classifieds/add_new/addNewCl_1_1",
type: 'POST',
dataType: 'json',
data: transfer_data,
success: function(data) {
console.log(data.response);
},
error: function (e) {
console.log(e.message);
}
});
and I want to receive it like that:
Array
(
[cl_name] => value
[contact_name] => value
[contact_lastname] => value
[contact_email] => value
[cl_alley] => value
[cl_services] => value
[cl_tags] => array(1 => value, 2 => value...)
)
so how I should be supposed to do it? I tried to print receiving data with print_r($_POST);
and I got only
Array
(
[cl_name] => value
[contact_name] => value
[contact_lastname] => value
[contact_email] => value
[cl_alley] => value
[cl_services] => value
)
I'm missing my cl_tags
with values
You need to change variable name in js
So working code are follow:
var data = {
q:1,
'w[]': [1,3,4,5,7],
'e[t1]': 1,
'e[t2]': 2,
'e[t3]': [1,2,3,4,5]
}
$.ajax({url:'/', type: 'POST', data: data});
In chrome debug we see follows:
q:1
w[]:1
w[]:3
w[]:4
w[]:5
w[]:7
e[t1]:1
e[t2]:2
e[t3][]:1
e[t3][]:2
e[t3][]:3
e[t3][]:4
e[t3][]:5
It is not a good idea to to push array like that.
JSON.stringify:It converts js object to json object.
Do this.
step1.Create array/object.
step 2.JSON.stringify(array) to encode your array in JavaScript,
step 3.$array=json_decode($_POST['jsondata']);//in your php
And one more thing:
you cannot provide numeric key to a javascript object.
for example:
var object = {
1:"wrong_way",
'1':true,
'alphabetic_key':"ideal";//boolean or number or string are valid as value.
}
Update:
As mentioned in the comment:
Its not the best of convention to use numbers as object keys.But if you do that the javascript engine will behind the scenes convert them in to strings.
But you have to be careful while accessing those object.
Object.'1';//valid
object.1;//invalid
object[1];//valid