extract json.stringify(data) - php

I'm building an API, and I need a little help, to understand how can I parse data from JSON request, here is my code:
<textarea style="width: 100%; height: 300px;" id="request_json">
{
"requestType":"TourListRequest",
"data":{
"ApiKey":"12345",
"ResellerId":"999",
"SupplierId":"999",
"ExternalReference":"12345",
"Timestamp":"2013-12-10T13:30:54.616+10:00",
"Extension":{
"any":{
}
},
"Parameter":{
"Name":{
"0":" "
},
"Value":{
}
}
}
}
</textarea>
<script>
function SubmitAPI() {
var sendInfo = {
JSON : $('#request_json').val(),
URL : $('#supplier_api_endpoint_JSON_Tour_List').val(),
Type : 'JSON Tour List'
};
$('#response_json').html("Calling API...");
$.ajax({
url: 'post_JSON.php',
type: "POST",
data: JSON.stringify(sendInfo), // send the string directly
success: function(response){
var obj = jQuery.parseJSON( response );
$('#response_json').html(response);
$('#response_validation').html( obj.json_valid );
},
error: function(response) {
$('#response_json').html(response);
}
});
}
</script>
So I need to know how to receive "JSON.stringify(sendInfo)" in my php script post_JSON.php
Any idea ?
Thank you in advance,

I think you need to name you data string, something like...
data: {info: JSON.stringify(sendInfo)},
and in your php:
$json_data = $_POST['info'];
var_dump(json_decode($json_data, true));
to get at that data using php, do something like:
$postedData = json_decode($json_data, true); // turns json string into an object
$requestType = $postedData['requestType'];
if you need to parse a returned json string with jquery you do something like this:
var jsonStuff = jQuery.parseJSON( data );
alert( jsonStuff.requestType);

I don't know php, but I think you have to do the below.
In the post_JSON.php, you can do: json_decode.

Related

appending a json file with PHP

I have a json file to which i'm trying to append data.
The json file content looks like this .
{
"KEYOP": ["01KEYOPS","23016/scripts/3rdParty/pusher-chat/assets/cobain.jpg"]
}
Below is my add_user.php
<?php
$sentArray = $_POST['dataString1'];
$boxArray = file_get_contents('results.json');
$sentdata = json_decode($sentArray);
$getdata = json_decode($boxArray);
foreach($sentdata as $value)
$getdata[] = $value;
print_r($getdata);
?>
and below is my jquery script where i'm trying to send data to server
var myObj = {foo: "bar", "baz": "wockaflockafliz"};
var jsonString = JSON.stringify(myObj, null, 2);
$.ajax({
type: "POST",
url: "23016/scripts/3rdParty/pusher-chat/server/add_user.php",
data: { 'dataString1': jsonString },
cache: false,
success: function(response)
{
alert(response);
}
});
The appended JSON file should look like this.
{
"KEYOPS01!": ["01 KEYOPS","23016/scripts/3rdParty/pusher-chat/assets/cobain.jpg"],
foo: "bar",
"baz": "wockaflockafliz"
}
I'm getting 500 Internal server error whenever I try to merge the data.
check the log, but, if you want to merge the 2 arrays ($sentdata and $getdata), you should use something like array_merge()
http://php.net/manual/es/function.array-merge.php
with this:
foreach($sentdata as $value)
$getdata[] = $value;
you are loosing your keys (and its slow)
and by the way... your appended json is not valid json...

How to retrieve data from jQuery.Post() in PHP?

I am currently trying to send a string to a to a php script which will eventually return a JSON file.
Here is code i'm using to send the string:
var str = "testString";
$.post("php/getTimes.php", str,
function(data){
console.log(data.name);
console.log(data.time);
}, "json");
In the 'getTimes' php file I am simply trying to receive the 'str' variable I am passing. Any ideas how to do this? It seems like it should be pretty simple.
You have to name attributes in POST data either with serialized string:
var data = "str=testString";
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
or with map:
var data = {
str : "testString"
};
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
To handle this variable in PHP use:
$str = $_POST['str'];
In getTimes.php:
<?php
$var = $_POST['string']; // this fetches your post action
echo 'this is my variable: ' . $var; // this outputs the variable
?>
Also adjust:
$.post("php/getTimes.php", str,
to
$.post("php/getTimes.php", { string: str },

Iterate over json array using jquery

There have been some post with my similar problem: How do I iterate over a JSON array using jQuery/AJAX call from PHP? but not quite the same.
I'm getting and error from jquery:
a is null
It is because of the code I've added to loop through the json data:
$(function ()
{
$.ajax({
url: 'ajax_dashboard/api.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
$.each(this, function(k, v) {
$('#output').append("<b>key: </b>"+k+"<b> value: </b>"+v)
.append("<hr />");
});
});
}
});
});
And here is the php file (which I did verify gives valid JSON format):
$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
echo json_encode($result_cameras);
?>
This returns this json formatted data:
[
{
"camera_name": "ffgg",
"camera_status": "DISABLED",
"camera_quality": "MEDIUM",
"email_notice": "DISABLED",
"camera_hash": "0d5a57cb75608202e64b834efd6a4667a71f6dee",
"camera_type": "WEBCAM"
},
{
"camera_name": "test",
"camera_status": "ENABLED",
"camera_quality": "HIGH",
"email_notice": "ENABLED",
"camera_hash": "6ab000ef7926b4a182f0f864a0d443fc19a29fdd",
"camera_type": "WEBCAM"
}
]
If I remove the loops the "a is null" error is gone. What am I doing wrong?
Your iteration code works just fine: http://jsfiddle.net/SuyMj/
The error is elsewhere.
Edit:
Try this to help debug.
success: function(data, textStatus, xhr) {
console.log(xhr);
...
}
xhr will contain a lot of information about the request being made. What does the responseText contain? What is the statusText?
Your code works fine:
http://jsfiddle.net/QSvNy/
So the error is not there.
I don't see that you set the Content-Type of your response from php. Possibly the mime type of your response is incorrect and so jQuery does not parse the response as json.
Try this in your php before you echo your json:
header('Content-Type: application/json');

How to get and process json data given by ajax request in prototype?

This is my first attempt to prototype. I want to initiate an AJAX request that should get a JSON response and alert that. I have done following so far.
JS:
<script type="text/javascript">
function ajaxRequest() {
var url = '/ajaxresponse';
new Ajax.Request( url, {
method: 'get',
onSuccess: function(transport,json) {
alert(json ? Object.inspect(json) : "no JSON object");
},
onFailure: function(){
alert('Something went wrong...')
}
});
}
</script>
HTML:
<a href='javascript:ajaxRequest();'>Testing AJAX</a>
JSON source:
function ajaxresponse() {
// Data
$data = array("New York", "New Yorkshire", "New Jersey");
// encode and return json data
echo json_encode( $data );
}
On clicking "Testing AJAX" link I am getting following result in alert box:
no JSON object
Any idea ?
Thanks
I dont see any second variable passed to onSuccess handler in prototype. Look here. There is only transport object. So this should help:
...
onSuccess: function(transport) {
var json = transport.responseText;
alert(json ? Object.inspect(json) : "no JSON object");
},
...

json stringify to php

I want to pass the key values into php page.
At php page, I will start to read value by matching ajaxcallid.
But it not working.
It gotta do with syntax/way I am passing in causing error.
parse error
invalid json: ajax call id is missing
JavaScript/AJAX:
var person = {
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
};
alert(person);
person= JSON.stringify(person);
alert(person);
$.ajax({
url: 'ROOT_URL/admin/ajaxtest.php',
type: "POST",
dataType: 'json',
data: {ajaxcallid: '26', jsarr: person},
timeout: 5000,
success: function(output) {
alert(output.Address);
},
});
PHP:
<?php
if (isset($_REQUEST['ajaxcallid']))
{
if($_REQUEST['ajaxcallid']==26)
{
//example, I want to read value of person.Address, person.City,
//person.PostalCode
//what is the easiest way
$phparr= json_decode($_REQUEST['jsarr']);
//do all other operation
$output= json_encode($phparr);
}
}
else
{
$output= "ajax call id is missing";
}
echo $output;
?>
If you are not using dataType : 'json', you might need to do stripslashes
$.post(window.data.baseUrl, {posts : JSON.stringify(posts)});
And in php:
$posts = json_decode(stripslashes($_POST['posts']));
This helped me:
data = json_decode($this->request->data['jsarr'], true);
in your php code for accessing the record
Hope it will help someone!
I'm going to take a guess and say that you SHOULDN'T stringify anything. I believe JQuery will do that for you. Namely, no person = JSON.stringify(person). Give that a try.
This is what your $.ajax call and the PHP side should look like:
JQuery
$.ajax({
url: "/admin/ajaxtest.php",
method: "POST",
data: {
ajaxcallid: "26",
person: JSON.stringify({
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : "99999"
})
}
}).done(function(data) {
if (!data) {
// generic error message here
} else if (data == 'invalid') {
alert('no ajaxcallid received');
} else {
var result = $.parseJSON(data); // if you pass back the object
alert(result.Address);
}
});
PHP
if (isset($_REQUEST['ajaxcallid'])) {
if ((int) $_REQUEST['ajaxcallid'] == 26) {
$personData = json_decode($_REQUEST['person']);
$address = $personData->Address;
$postalCode = $personData->PostalCode;
$returnData = json_encode($personData);
echo $personData;
die();
}
} else {
echo 'invalid';
die();
}
$data_array = json_decode($json_string);
If you want objects to be converted into associative arrays, then add true into function:
$data_array = json_decode($json_string, true);
I have not worked with PHP but from my experience with ASP.net following may help you.
Add contentType key to ajax settigns:
type: "POST",
contentType:'application/json',
dataType: 'json',
also I think you need to stringify whole value you are assigning to data like this:
var person = {
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
};
var d= {ajaxcallid: '26', jsarr: person};
var dat=JSON.stringify(d);
......
data: dat,
......

Categories