I have a php script which returns a JSON string.
<?php
$arr = array(
'id' => '1',
'myarray' => array(
array('a' => 'a1', 'b' => 'b1', 'c' => 'c1', 'd' => 'd1'),
array('a' => 'a2', 'b' => 'b2', 'c' => 'c2', 'd' => 'd2')
)
);
echo json_encode($arr);
?>
The javascript code for parsing the JSON is
$.ajax({
dataType: "json",
url: "http://www.something.com/sendJson.php"
}).done(function(json) {
data = jQuery.parseJSON(json);
alert(data['id']);
});
But for the above code i'm getting this error
SyntaxError: JSON Parse error: Unexpected identifier "object"
What could be causing this error?
The problem is your ajax call. You have dataType: "json", which means your string is already parsed in the callback.
So:
$.ajax({
dataType: "json",
url: "http://www.something.com/sendJson.php"
}).done(function(json) {
alert(json['id']);
});
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']
}
}
}
I am using x editable for inline editing.
JQUERY
$('#status').editable({
value: 2,
source: [
{value: 1, text: 'Active'},
{value: 2, text: 'Blocked'},
{value: 3, text: 'Deleted'}
]
});
This one is running fine. But the problem is, I want to get source options from php. For that I have an array.
PHP
$php_array = Array ( [MOBILE_TOPUP] => MOBILE_TOPUP
[PICKUP] =>PICKUP
[DELIVERY] => DELIVERY
[BANK_DEPOSIT] => BANK_DEPOSIT )
I tried with by passing below variable in source but it's not working:
var json_array = <?=json_encode($php_array)?>;
How can I achieve this? Do I need to change array structure in PHP? Thanks for any help!
Yes, you have to change array structure as below :
$php_array = Array (
array('value' => 1, 'text' => 'Active'),
array('value' => 2, 'text' => 'Blocked'),
array('value' => 3, 'text' => 'Deleted'),
);
var json_array = '<?=json_encode($php_array)?>';
You shouldn't use PHP inside JS, better to make an ajax call. This feature is built into x-editable if you use the source option with a string like so:
$('#status').editable({
value: 2,
source: 'mypage.php'
});
I have a form and I am sending it with ajax to server.
Like this:
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize(),
dataType : 'json',
success: function(data){
}
});
And I receive in server something like
Array
(
[forms_element_1] => 'some value 1',
[forms_element_2] => 'some value 2',
[forms_element_3] => 'some value 3'
)
Now i need to add to this form global variable that is array itself.
var statuses = [5,7,3];
I need to receive from POST in server side something like
Array
(
[forms_element_1] => 'some value 1',
[forms_element_2] => 'some value 2',
[forms_element_3] => 'some value 3',
[statuses] => Array
(
[0] => 5,
[1] => 7,
[2] => 3
)
)
How can I achieve that in jQuery?
Turn it into a param string with $.param, then append it to the serialized form (which is also a param string).
data: form.serialize() + "&" + $.param({statuses:[5, 7, 3]}),
I am passing data to my php script using jQuery's .ajax method. I am passing a very complex JSON object as data. At server side I receive data in $_POST variable all converted to php format.
How this conversion happen? Does it happen at the client side or the server side? Which modules associated in this process. Any source to understand complete process in depth.
Client request:
var data = {
foo: 123,
bar: 456,
rows: [
{
column1 : 'hello',
column2 : 'hola',
column3 : 'bonjour',
},
{
column1 : 'goodbye',
column2 : 'hasta luego',
column3 : 'au revoir',
},
],
test1:{
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
At Server Side My '$_POST' var:
Array
(
[foo] => 123
[bar] => 456
[rows] => Array
(
[0] => Array
(
[column1] => hello
[column2] => hola
[column3] => bonjour
)
[1] => Array
(
[column1] => goodbye
[column2] => hasta luego
[column3] => au revoir
)
)
[test1] => Array
(
[test2] => Array
(
[test3] => baz
)
)
)
This code snippet is taken from here.
Jquery is converting the data into HTTP format. http://en.wikipedia.org/wiki/POST_%28HTTP%29
This link shows how arrays are encoded: http://php.net/manual/en/function.http-build-query.php
You can use PHP itself to generate the HTTP format. I converted your array to PHP format:
$data = array( 'foo' => 123,
'bar' => 456,
'rows' => array( 0 => array( 'column1' => 'hello',
'column2' => 'hola',
'column3' => 'bonjour'),
1 => array( 'column1' => 'hello',
'column2' => 'hola',
'column3' => 'bonjour')),
'test1' => array('test2' => array('test3' => 'baz')) );
Then you can generate the HTTP as follows:
echo http_build_query($data);
I got the following result:
foo=123&bar=456&rows%5B0%5D%5Bcolumn1%5D=hello&rows%5B0%5D%5Bcolumn2%5D=hola&rows%5B0%5D%5Bcolumn3%5D=bonjour&rows%5B1%5D%5Bcolumn1%5D=hello&rows%5B1%5D%5Bcolumn2%5D=hola&rows%5B1%5D%5Bcolumn3%5D=bonjour&test1%5Btest2%5D%5Btest3%5D=baz
JSON is a universal data exchange format (to all languages that support its specification that is). The JSON data is encoded from a memory object to a JSON-formatted string by the language that is sending it, and decoded (from string to object) by the language that receives it.
An important point when talking about jQuery and JavaScript is that the syntax for a JSON looks similar to JavaScript, but it is actually more strict than the syntax for a regular JavaScript Object (see: What are the differences between JSON and JavaScript object?). For example, the JavaScript object literal you have posted above is not valid JSON, becuase both the keys and values are not surrounded by quotes. Additionally, there is technically no such thing as a JSON Object. A glob of JSON data is acutally just a String written in a subset of JavaScript's Object Notation.
So, PHP's json_encode($object) function and jQuery's encodeJSON([Object]) function will transform a memory object in their respective languages into a string that both languages (and others of course) can accept as data. The json_decode($string) and parseJSON([String]) functions in PHP and jQuery, respectively, take a JSON string and commit it to memory as an object.
jQuery encodes the object data as a key value pairs, for example if we have:
var data = {
foo: 123,
bar: 456,
rows: [
{
column1 : 'hello',
column2 : 'bonjour',
},
{
column1 : 'goodbye',
column2 : 'au revoir',
},
]
};
jquery will encode that object to the following string
foo=123&bar456&rows[][column1]=hello&rows[][column2]=bonjour&rows[][column1]=goodbye&rows[][column2]=au+revoir
and PHP will convert that string in to an array and assign it to the $_GET or $_POST array depending of the request.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
multi-dimensional array post from form
I would like to send some data from the client to the PHP server using jQuery $.post(). When it arrives at the server, I would like $_POST['myList'] to be equal to either of the following (what ever is easiest). What should I set the data object to within $.post()?
array (
0=>array('id'=>123,'d1'=>'aaa','d2'=>'xxx'),
1=>array('id'=>234,'d1'=>'bbb','d2'=>'yyy'),
2=>array('id'=>345,'d1'=>'ccc','d2'=>'zzz')
)
array (
123=>array('d1'=>'aaa','d2'=>'xxx'),
234=>array('d1'=>'bbb','d2'=>'yyy'),
345=>array('d1'=>'ccc','d2'=>'zzz')
)
EDIT: first one looked like a simple array of objects, but seems jQuery needs this to be a keyed object:
var send_this = {
0: { id: 123, d1: 'aaa', d2: 'xxx' },
1: { id: 234, d1: 'bbb', d2: 'yyy' },
2: { id: 345, d1: 'ccc', d2: 'zzz' }
};
Second looks just has different looking keys for object containing objects:
var send_this = {
'123': { d1: 'aaa', d2: 'xxx' },
'234': { d1: 'bbb', d2: 'yyy' },
'345': { d1: 'ccc', d2: 'zzz' }
};
Tested implementation in jQuery 1.7.1:
$.post( '/herp.php', send_this, function(d) {
console.info( d );
});
The PHP program receives data exactly as you want it in $_POST.
You should use a JSON strong to send the data: Here is an example:
var pushData = {
id: "blalal",
id: "blalal",
id: "blalal",
};
JSON.stringify(pushData)
and then you can just post it or whatever
$.ajax({
url : "http://blalallalalal="+JSON.stringify(pushData),
type : "POST",
dataType: "text",
success: function (data) {
},
error: function() {
// alert("fsdf");
}
});
then from php side just use
$data = get_object_vars(json_decode($dataJSON));
DONE
Option 1
var data = [
{ id: 123, d1: 'aaa', d2: 'xxx' },
{ id: 234, d1: 'bbb', d2: 'yyy' },
{ id: 345, d1: 'ccc', d2: 'zzz' }
];
Option 2
var data = {
'123': { d1: 'aaa', d2: 'xxx' },
'234': { d1: 'bbb', d2: 'yyy' },
'345': { d1: 'ccc', d2: 'zzz' }
};
then
$.post(url, {mylist: data});
If your using jQuerys $.post or $.get, you do not need to encode/decode, just pass a JS object as the data argument...
var data = {
"myList" : {
0 : {"id":1,...etc},
1 : {"id":2,...etc},
2 : {"id":3,...etc},
etc...
}
};
// post or get
$.post(
url2post,
data,
callbackFunc
);
You could send them as three arrays, one for each attribute.
myList_id[]=123&myList_d1[]=aaa&myList_d2[]=xxx&myList_id[]=234&...
In PHP, you will recieve them as $_POST['myList_id'], $_POST['myList_d1'] and $_POST['myList_d2'], which you could combine into your desired array.
Or if you include indices, you could go a step further:
myList[0][id]=123&myList[0][d1]=aaa&myList[0][d2]=xxx&myList[1][id]=234&...
which will give you the array directly: $_POST['myList']