I am trying to pass a multiple part array via ajax to a PHP function.
This is my JS:
var datastring = {
newEmailForm: newEmailForm,
properties: properties
};
//got the data, make the ajax request
jQuery(function(){
jQuery.ajax({
type:'POST',
data:{
action: 'elegantSendEmail',
datastring: datastring
},
url: ajaxurl
})
})
This is the array thats being sent:
action elegantSendEmail
datastring[newEmailForm][0][] {…}
0 email
1 title
2 Message
datastring[properties][0][] {…}
0 31466
1 value1
2 value1
datastring[properties][1][] {…}
0 31440
1 value2
2 value2
Here is my attempt at trying to get at it via PHP but i just get nothing in my response.
function elegantSendEmail(){
var_dump($_POST);
wp_die();
}
Here is the result of the dump from my console:
array(2) {
["action"]=> string(16) "elegantSendEmail"
["datastring"]=> array(1) {
["newEmailForm"]=> array(1) {
[0]=> array(3) {
[0]=> string(5) "email"
[1]=> string(5) "title"
[2]=> string(17) "Youe message here"
}
}
}
}
$obj = json_decode($_POST['datastring']['newEmailForm'][0], true);
Try this
function elegantSendEmail() {
$obj = $_POST['datastring']['newEmailForm'][0][0];
var_dump($obj);
//Above dump shows 'email'
wp_die();
}
You need to send data with proper json format in ajax. for example
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
So based on your answer and after var_dump
the $_POST
result we see that you pass an array and not a json object. So you can access it's fields like a normal array.
$obj=$_POST['datastring']['newEmailForm'][0][0] // will get you the email
$obj=$_POST['datastring']['newEmailForm'][0][1] // will get you the title
$obj=$_POST['datastring']['newEmailForm'][0][2] // will get you the message
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.