json stringify to php - 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,
......

Related

Undefined Variable in Ajax from PHP

I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}

returning an array from ajax call

trying to get 2 values from an ajax call, cant seem to breakup the results back form the call
the ajax
$.ajax({
type:'POST',
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
alert(lname);
}
});
the php
$datas = $database->select("Drivers", "*", [
"id" => $q]);
if (count($datas)>0) {
foreach($datas as $data){
$fname=$data['first_name'];
$lname=$data['last_name'];
}
$rdata = array(
'fname'=> $fname,
'lname'=> $lname
);
echo $rdata; //$datas['first_name']
} else {
echo 'no datas';
}
trying to find the lastname only.
thank in advance
Jeff
Change to this:
$.ajax({
type:'POST',
dataType: 'json', // <-- specify that your return type should be JSON
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
if (data.fname && data.lname) {
var firstName = data.fname;
var lastName = data.lname;
}
}
});
when working with arrays you need to use JSON data type.
Your PHP: echo json_encode($rdata);
You can use json_encode() function in your PHP file
echo json_encode($rdata);
Use json_encode() in PHP to serialize your data first as Paramore has explained.
In javascript your success function callback has a parameter of "data", "lname" is not defined in that context so to access fname and lname you need to do like so:
data.lname
data.fname

extract json.stringify(data)

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.

Reading JSON from database into combobox using jQuery .each()

I need to be able to select a country in a selectbox, and then get all the states from that country.
I'm trying to do something like this: how-to-display-json-data-in-a-select-box-using-jquery
This is my controller:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
and my javascript:
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
success: function (data) {
console.log(data);
}
});
console.log shows me something like this:
["71","SomeState0"]["72","SomeState"]["73","SomeState2"]["74","SomeState3"]
So, what i need is to append all states in a new selectbox.
But I'm trying to read this array doing this in the success callback:
$.each(data, function(key,val){
console.log(val);
});
In the result, each line is a word, like this:
[
"
7
1
"
,
"
s
....
]
Why does that happen, and what am I missing?
JSON is not made of independent blocks. So this will never do:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
The output will be treated as text, and the iterator will loop the object's elements... which are the single characters.
You need to declare a list, or a dictionary. I have included some examples, depending on how you use the data in the jQuery callback. Note: PHP-side, you may also need to output the proper MIME type for JSON:
$states = array();
foreach($this->settings_model->get_state_list() as $state)
{
// Option 1: { "71": "SomeState0", "72": "Somestate2", ... }
// Simple dictionary, and the easiest way IMHO
$states[$state->CODSTA] = $state->STANAM;
// Option 2: [ [ "71", "SomeState0" ], [ "72", "SomeState2" ], ... ]
// List of tuples (well, actually 2-lists)
// $states[] = array($state->CODSTA, $state->STANAM);
// Option 3: [ { "71": "SomeState0" }, { "72": "SomeState2" }, ... ]
// List of dictionaries
// $states[] = array($state->CODSTA => $state->STANAM);
}
Header('Content-Type: application/json');
// "die" to be sure we're not outputting anything afterwards
die(json_encode($states));
In the jQuery callback, you specify the datatype and content type with charset (this will come in handy as soon as you encounter a state such as the Åland Islands, where a server sending data in ISO-8859-15 and a browser running a page in UTF8 can lead to a painful WTF moment):
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#comboId").get(0).options.length = 0;
$("#comboId").get(0).options[0] = new Option("-- State --", "");
// This expects data in "option 1" format, a dictionary.
$.each(data, function (codsta, stanam){
n = $("#comboId").get(0).options.length;
$("#comboId").get(0).options[n] = new Option(codsta, stanam);
});
},
error: function () {
alert("Something went wrong");
}
have you tried using $.map() instead?
http://api.jquery.com/jQuery.map/
$.map(data, function(index, item) {
console.log(item)
})
You should use GET not POST since you are not actually creating anything new serverside.
Read a bit about REST and why using GET is the proper noun here.
I've added a JSFiddle example that you can run straight away.
http://jsfiddle.net/KJMae/26/
If this is the JSON that the PHP service returns:
{
"success":true,
"states":[
{
"id":71,
"name":"California"
},
{
"id":72,
"name":"Oregon"
}
]
}
This is our HTML code:
<select id="country">
<option value="">No country selected</option>
<option value="1">USA</option>
</select>
<select id="states">
</select>​
This is what the code to add that to the select could look like:
// Bind change function to the select
jQuery(document).ready(function() {
jQuery("#country").change(onCountryChange);
});
function onCountryChange()
{
var countryId = jQuery(this).val();
$.ajax({
url: '/echo/json/',
type: 'get',
data: {
countryId: countryId
},
success: onStatesRecieveSuccess,
error: onStatesRecieveError
});
}
function onStatesRecieveSuccess(data)
{
// Target select that we add the states to
var jSelect = jQuery("#states");
// Clear old states
jSelect.children().remove();
// Add new states
jQuery(data.states).each(function(){
jSelect.append('<option value="'+this.id+'">'+this.name+'</option>');
});
}
function onStatesRecieveError(data)
{
alert("Could not get states. Select the country again.");
}​
As for the PHP, here's a simple example that should give the same result as JSON used in example above. (Haven't tested it, from top of my head, no php here.)
$result = new stdClass;
$result->states = array();
foreach($this->settings_model->get_state_list() as $state)
{
$stateDto = new stdClass();
$stateDto->id = $state->CODSTA;
$stateDto->name = $state->STANAM;
$result->states[] = $stateDto;
}
$result->success = true;
die(json_encode($result));

undefined error with ajaxcall to receive json data

my problem is that I
can not solve this problem
If I call the php script, all I get is an undefined error
this is the code I use for testing AND
this is the original code from the creator that is giving me a headache
function startJsonSession(){
$.ajax({ url: "jsontest.php?action=startjson",
cache: false,
dataType: "json",
complete: function(data) {
username = data.username;
alert(username);
}
});
}
//phpscript
if ($_GET['action'] == "startjson") { startJson(); }
function startJson() {
header('Content-type: application/json');
$items = '';
echo json_encode(array(
"username" => "bob",
"items" => array( "item1" => "sandwich",
"item2" => "applejuice"
)
));
}
thanks, Richard
edited my question because:
this function returns the json data in a different way
and therefore the solution presented below, does not have the same outcome.
function startChatSession() {
$items = '';
if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
$items .= chatBoxSession($chatbox);
}
}
if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
exit(0);
}
I recreated with your code and figured it out. The object being returned is of type XMLHttpRequest. Its got a property called responseText holding a json string with the data.
so this works..
var decodedData = eval("(" + data.responseText + ")");
username = decodedData.username;
alert(username);
A bit messy but it does the trick :-)
p.s If it helps, I figured it out using firebug in firefox and sticking a breakpoint in the js code
Edited below:
Without wanting to do the eval, you could use this and it works:
$.getJSON("json.php?action=startjson",
function(data) {
username = data.username;
alert(username);
}
);
Edited to show what I did with the success function:
$.ajax({
url: "json.php?action=startjson",
cache: false,
dataType: "json",
success: function(data) {
username = data.username;
alert(username);
}
});
Is username a global variable?
If not you should prepend the "var" keyword.
username = data.username -> var username = data.username;
At the end I got it working.
I installed firebug and saw that the php script was returning html headers instead off json.
All off the sudden it started working, I really would like to know what the problem was, but I can't tell you.
Anyway, thanks for sticking so long, David
also what I don't understand is that it breaks out off php mode, instead of echoing it back like it's done with xml
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
is this the same as above (object array containing literal array)?
echo json_encode(array(
"username" => "bob",
"items" => $items
)
));
}

Categories