I have a PHP script that sends this array to the client via ajax:
Array
(
[0] => $209.90
[1] => $20.99
[2] => $188.91
)
I am sending the array to the client this way:
return $servicePrices;
I have this jQuery statement:
success: function(data) {
//console.log('Success'+data);
$( '#tourSubtotal' ).val( data[0] );
$( '#tourDiscount' ).val( data[1] );
$( '#tourTotal' ).val( data[2] );
},
My results for each ID value are A, r and r. Instead, how can I get the 3 currency data values from the array in my ajax jQuery?
It looks like you are using print_r() function to display this:
Array
(
[0] => $209.90
[1] => $20.99
[2] => $188.91
)
In that format it's just as useful as any string is. You have to use json_encode() to convert it to a format both languages understand like:
["$209.90", "$20.99", "$188.91"]
Your PHP code should be something like:
<?php
$json = some_value;
// Remove this:
// print_r($json);
// Instead, write this:
echo json_encode($json);
?>
And then you can use it in JavaScript, the way you have specified. Also, jQuery is smart enough to understand that the response is JSON and you don't need JSON.parse() in most of the cases.
You can return the array in a JSON encoded format from PHP as mentioned below:
$result = array(
'0' => '$209.90'
'1' => '$20.99'
'2' => '$188.91'
);
return json_encode($result);
And on the AJAX success function you can use :
success: function(data) {
var temp = JSON.parse(data);
$( '#tourSubtotal' ).val( temp[0] );
$( '#tourDiscount' ).val( temp[1] );
$( '#tourTotal' ).val( temp[2] );
},
Hope this helps.
Related
I have a large multi-dimensional object of arrays in JS that I am trying to pass to PHP using Ajax. The keys of some of the array values are written arrays test[key], and in PHP I want them to be read as such test => array([key] => 123). Note, I am working in Wordpress.
Working example
JS:
var args = {
'action' : 'save',
'test[key1]' : ['123', 'abc']
}
var request = $.ajax({
url: settings.get('ajaxurl'),
data: args,
type: 'post',
success: function(response) { // }
});
PHP print_r on output:
[action] => save
[test] => Array
(
[key1] => Array
(
[0] => 123
[1] => 234
)
)
However, I want to send all of the test[key1] (and a lot more data) at the second level of the object. I have a lot of data and need them grouped accordingly.
Not working example
JS:
// simple changing the args
var args = {
'action' : 'save',
'data' : {
'test[key1]' : ['123', 'abc']
}
}
PHP print_r on output:
[action] => save
[data] => Array
(
[test[key1] => Array
(
[0] => 123
[1] => 234
)
)
This seems to be really difficult to explain - but it looks like PHP isn't parsing the array keys properly when it's not on the top level of the array. Am I doing something wrong // is there a way around this? I can provide more insight if needed, I attempted to make this as clear as possible.
When printing the keys of the data array, it prints them without the final ]. So it shows test[key1 instead of what I am expecting. Maybe they get stripped somewhere?
I think you need to stringify the data
var request = $.ajax({
url: settings.get('ajaxurl'),
data: JSON.stringify(args),
type: 'post',
success: function(response) { // }});
Then use json_decode to make it useful in PHP.
Edit:
This might get you where you want to go...
var args = {
'action' : 'save',
test : {
key1 : [
'123',
'abc' ]
} }
Since JavaScript does not allow for associative arrays.
Please try this args, this will give multi-dimensional array result.
var args = {
'action' : 'save',
'data' : {
'test': {
'key1' : ['123', 'abc']
}
}
}
This question already has answers here:
Issue reading HTTP request body from a JSON POST in PHP [duplicate]
(2 answers)
Closed 4 years ago.
I am trying to pass a Json obtained by a json.stringify process of an html table to a php file to insert it into a database.
First,wanted to check is the code below is ok : i get the right output of the json when doing an alert of 'myjson':
var myjson= JSON.stringify(mydata);
alert(myjson);
[{},{"product[]":"john","qty[]":"288","price[]":"199","total[]":"57312"},{"product[]":"sylvia","qty[]":"12","price[]":"13","total[]":"156"},{"product[]":"juan","qty[]":"11","price[]":"9","total[]":"99"},{"total_amount":"57567.00"}]
then i have this ajax to send it to php (test.php):
$.ajax({
url: "test.php",
type: "POST",
data: myjson,
dataType: "JSON",
success: function (data) {
alert(data);
}
});
And my php file to check if the output is fine:
$obj = json_decode($_POST["mydata"]);
echo $obj->var;
but i do not get anything in my alert once the php is supposedly processed?
what is wrong?
Firstly, you will need to post the data with a name, more specifically with the name "mydata".
Currently the PHP looking for a post called mydata ($_POST["mydata"]) which is not available and throws the following Notice Undefined index: mydata
To do that, you can change the data you're sending from:
data: myjson
to
data: {"mydata": myjson}
Second, the data sent to the back-end is an array of objects
Array
(
[0] => stdClass Object
(
)
[1] => stdClass Object
(
[product[]] => john
[qty[]] => 288
[price[]] => 199
[total[]] => 57312
)
[2] => stdClass Object
(
[product[]] => sylvia
[qty[]] => 12
[price[]] => 13
[total[]] => 156
)
[3] => stdClass Object
(
[product[]] => juan
[qty[]] => 11
[price[]] => 9
[total[]] => 99
)
[4] => stdClass Object
(
[total_amount] => 57567.00
)
)
You will need to access them by index or iterate through the array.
Access them by index: $obj[0]->var or $obj[1]->var
Last but not least, the properties contain square brackets {"product[]":"john","qty[]":"288","price[]":"199","total[]":"57312"} which is not recommended but will still work. Accessing the properties should be done like: $obj[1]->{'property[]'}
JavaScript:
<script type="text/javascript">
function sendAjax(){
var mydata = [{}, {"product[]":"john","qty[]":"288","price[]":"199","total[]":"57312"}, {"product[]":"sylvia","qty[]":"12","price[]":"13","total[]":"156"},{"product[]":"juan","qty[]":"11","price[]":"9","total[]":"99"},{"total_amount":"57567.00"}]
var myjson = JSON.stringify(mydata);
$.ajax({
url: "test.php",
type: "POST",
data: {"mydata": myjson},
dataType: "JSON",
success: function (data) {
alert(data);
}
});
}
</script>
PHP:
<?php
$obj = json_decode($_POST["mydata"]);
echo $obj[1]->{'product[]'};
?>
Update:
The AJAX is expecting a JSON response, otherwise it will fail. In the Back-End you will need to change the response to JSON.
<?php
$obj = json_decode($_POST["mydata"]);
header('Content-Type: application/json');
echo json_encode($obj[1]->{'product[]'});
?>
I am aware, that there are many questions regarding this topic in general... however, so far I haven't found a solution to my specific problem:
I have objects, looking something like that:
var myArray = [];
var ArrayObject = {
power: 10,
name: 'arrayobject'
}
myArray.push(ArrayObject);
var myObject = {};
myObject.Name = "test";
myObject.myArray = myArray.slice(0);
Now I would like to post this data to php:
post("./output.php", myObject,'post');
Well, this does not work... I also tried it with
var myJSON = JSON.stringify(myObject);
and on PHP Side with
//$myObj = json_decode($_GET['myObject']);
but that does not work as well... if I remove the 'myArray' from 'myObject' that works, but having all data in one object would be very nice.
Can anyone tell me how to do that or point me in the right direction?
Thank you very much!
If you make request like this
function test(){
var myArray = [];
var ArrayObject = {
power: 10,
name: 'arrayobject'
}
myArray.push(ArrayObject);
var myObject = {};
myObject.Name = "test";
myObject.myArray = myArray.slice(0);
jQuery.post('output.php', {
data: {
myObject:myObject
},
}, function(data) {
console.log(data);
});
}
then you access the data in PHP like
$_POST['data']['myObject']
Whole $_POST will look alike
array (
'data' =>
array (
'myObject' =>
array (
'Name' => 'test',
'myArray' =>
array (
0 =>
array (
'power' => '10',
'name' => 'arrayobject',
),
),
),
),
)
You don't need to json_decode it automatically does
I am trying to loop through a multidimensional associative array retrieved via jquery/ajax from a php file.
The php array looks like this:
$pink = array ( "newarray" => array
( "varietyOne" => array
("name" => "Poublout", "year" => 2002),
"varietyTwo" => array
("name" => "Gerarde", "year" => 2003),
"varietyThree" => array
("name" => "Encore", "year" => 1956),
"varietyFour" => array
("name" => "Toujours", "year" => 1957),
"varietyFive" => array
("name" => "J'aime", "year" => 1958),
"varietySix" => array
("name" => "Alisee", "year" => 2001)
),
"varNumber" => array
("varietyOne",
"varietyTwo",
"varietyThree",
"varietyFour",
"varietyFive",
"varietySix"
)
);
print json_encode($pink);
The js looks like this:
$(document).ready(function () {
$('.clicker').click(function () {
$.ajax({
type: 'GET',
url: 'another.php',
dataType: 'json',
success: function (brandon) {
for (var i = 0; i < brandon.newarray.length; i++) {
var catName = brandon.varNumber[i];
for (var wineName in brandon.newarray[i][catName]) {
console.log(branond.newarray[i][catName][wineName]);
}
}
}
});
});
});
And here is the json rather than the php:
{"newarray":
{"varietyOne":{"name":"Poublout","year":2002},
"varietyTwo":{"name":"Gerarde","year":2003},
"varietyThree":{"name":"Encore","year":1956},
"varietyFour":{"name":"Toujours","year":1957},
"varietyFive":{"name":"J'aime","year":1958},
"varietySix":{"name":"Alisee","year":2001}},
"varNumber":
["varietyOne","varietyTwo","varietyThree","varietyFour","varietyFive","varietySix"]}
I've tried several different loops, changing my array values, but I can't make anything work. I can call an individual key=value pair in the array, but I can't get it to loop through all values.
Thank you.
And the results of console.log(brandon)
Object { newarray={...}, varNumber=[6]}
newarray
Object { varietyOne={...}, varietyTwo={...}, varietyThree={...}, more...}
varietyFive
Object { name="J'aime", year=1958}
varietyFour
Object { name="Toujours", year=1957}
varietyOne
Object { name="Poublout", year=2002}
varietySix
Object { name="Alisee", year=2001}
varietyThree
Object { name="Encore", year=1956}
varietyTwo
Object { name="Gerarde", year=2003}
varNumber
["varietyOne", "varietyTwo", "varietyThree", 3 more...]
0 "varietyOne"
1 "varietyTwo"
2 "varietyThree"
3 "varietyFour"
4 "varietyFive"
5 "varietySix"
So, the loop now outputs to console, but I want the text to be displayed on my site. Normally I use a $('#somediv').append(brandon.(whateverelse); and the information will appear. In this case it does not.
You shouldn't need the varNumber array.
All you need is:
for (var index in brandon.newarray) {
console.log(index);
console.log(brandon.newarray[index]);
console.log(brandon.newarray[index]['name']); // or brandon.newarray[index].name
console.log(brandon.newarray[index]['year']); // or brandon.newarray[index].year
}
In this case, index will be varietyOne, varietyTwo, etc.
How can I post a JSON multi-dimensional data via $.post? For instance, I have this multi-dimensional array in JSON format:
{
"file":
{
"name" : "1024x768.jpg",
"type" : "image\/jpeg",
"tmp_name" : "C:\\wamp\\tmp\\php8F59.tmp",
"error":0,"size":469159
}
}
I will use Jquery.post() to post the JSON data.
$.post("process.php",'{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}',function(xml){
});
So I can get this array in process.php using print_r($_POST):
Array
(
[file] => Array
(
[name] => 1024x768.jpg
[type] => image/jpeg
[tmp_name] => C:\wamp\tmp\phpA1.tmp
[error] => 0
[size] => 469159
)
)
Is this possible?
Try this:
$.post("process.php",{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}},function(xml){
});
that should give you the desired array on the php side
Edit: this works since jQuery 1.4 and above
$jsonArray ='{"file":{"name":"1024x768.jpg","type":"image\/jpeg","tmp_name":"C:\\wamp\\tmp\\php8F59.tmp","error":0,"size":469159}}';
$arr = JSON.stringify($jsonArray);
$.post("/url",{data:$arr},function(){
});
in the php file do
$json = json_decode($_POST['data']);
print_r($json);
Edit
may be this will help, i have not tested it though...
var file=[];
file["name"]="1024x768.jpg";
file["type"]="image/jpeg";
file["tmp_name"]="C:\wamp\tmp\phpA1.tmp";
file["error"]="0";
file["size"]="469159";
var myObject = new Object();
var enumm=["name","type","tmp_name","error","size"];
function getEnum(index){
return enumm[index];
}
$.each(file,function(i,j){
myObject[getEnum(i)]=file[getEnum(i)];
});
$.post("/url",{data:$.param(myObject)},function(xml){
});
on the php side do
$json = parse_str($_POST['data'], $data);
print_r($json);