how to create correct PHP json response - javascript

Hello i have a page can calla an ajax page in json with jquery.
i just set
dataType: "json"
in ajax call and i set header in php
header("Content-type: application/json; charset=utf-8");
but when i try read my response in a client i have this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var o = JSON.parse(jsonString);
For more information
PHP file function:
function _addToWishlist($v,$db){
$ris = array();
$data = array();
$data[0]=20;
$data[1]=25;
$data[2]=30;
$ris['stato']="1";
$ris['mex']="DA IMPLEMENTARE!!!";
$ris['data']=$data;
$ris['action']="";
ob_clean();
echo json_encode($ris);
}
and thi is a php response:
{"status":"success","stato":"1","mex":"DA IMPLEMENTARE!!!","data":[20,25,30],"action":""}
in client i use this javascript:
$.ajax({
url: "common/function/include/dataLoad.php",
type: "POST",
data: datas,
async:false,
//dataType: "text",
dataType: "json",
success: function(ris) {
// Run the code here that needs
// to access the data returned
//$(this).parent
//alert (ris);
risp=ris;
//var a = JSON.parse(ris);
tryParseJSON(ris);
//return ris;
},
error: function() {
alert('Errore di rete');
}
}).done(function(){
if(divwhere!=""){
$(divwhere).html(risp);
}
if(actionAfter!=""){
eval(actionAfter);
}
});
the function for test json is here: stackoverflow
how can i do for create a correct call json? thank you very much

jQuery will automatically parse a JSON response for you - you don't need to do it again. The returned ris object is ready for you to work with as-is. Assuming the request works, there is no problem with the format of your PHP response.
success: function(ris) {
console.log(ris.status); // = 'success'
console.log(ris.mex); // = 'DA IMPLEMENTARE!!!'
},

Related

How to can I print an array transferred from javascript to php from $_POST

I am trying to transfer a javascript array to a php array and I used the following code in my php file to do so:
var rowArr=[];
var currow=$(this.closest('tr'));
var col1=currow.find('td:eq(0)').text();
rowArr.push(col1);
var col2=currow.find('td:eq(1)').text();
rowArr.push(col2);
var col3=currow.find('td:eq(2)').text();
rowArr.push(col3);
var myJSONText = JSON.stringify( rowArr );
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function() {
alert("Success");
}
});
so when I run this code, I get the success alert but I am not seeing any of the array elements being printed out. I am also not getting any error messages.Here is my jsonRecieve.php:
<?php
$rowAr=$_POST['emps'];
print_r($rowAr);
?>
is there a way to verify that it has been transferred? I don't believe it has but if it hasn't can someone help?
Seems you need to decode the json string with json_decode() to get your emps value on the server side and to alert the server response need to send something from the server. Let's debug this way-
ON JS
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function(data) {
alert(data); // alert your data to see that returns from server
}
ON PHP
<?php
$rowAr=$_POST['emps'];
$array = json_decode($rowAr,1); // 2nd params 1 means decode as an array
print_r($array);
die('response from the server');
?>

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

send multidimensional array to php using ajax as json and receive html text to show in a div

First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});

Saving ajax POST data with PHP

I've been trying to save some data to a .json file with ajax and php.
At the moment I'm receiving an error and my data is not being saved and can't figure out why.
This is my .js file:
var data = {
"test": "helloworld"
}
$.ajax({
url: "save.php",
data: data,
dataType: 'json',
type: 'POST',
success: function (data) {
$("#saved").text("Data has been saved.");},
error: function (data){
$("#saved").text("Failed to save data !");}
});
And here is my php file:
$json = $_POST['data'];
if(json_decode($json) != null){
$file = fopen('web/js/data_save.json', 'w+');
fwrite($file, json_encode($json));
fclose($file);
}else{
print("<pre>Error saving data !</pre>");
}
When I'm trying to save the ajax error is getting triggered:
error: function (data){
$("#saved").text("Failed to save data !");
}
I hope someone can guide me in the right direction :)
this works fine for me
.js:
$(document).ready(function() {
var json_object = {"data": "helloworld"};
$.ajax({
url: "../tests/save.php",
data: json_object,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$("#saved").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$("#saved").text("Failed to save data !");
}
});
});
.php
$post_data = $_POST['data'];
if (!empty($post_data)) {
$file = fopen('data_save.json', 'w+');
fwrite($file, json_encode($post_data));
fclose($file);
echo json_encode('success');
}
if you do a var_dump on the $_POST you ll see that your variable is sent as an array in php. also you need to echo a json string for the callback success
You do not have any key data in your request.
You need to parse the whole request body as JSON with http_get_request_body or something to get the raw body in order to get the result you want.
EDIT: As it seems that there has been some confusion, here are some further explanations.
When sending a JSON POST request to PHP, you cannot use the $_POST variable as you would with a normal request.
curl -H 'Content-Type: application/json' -d '{"foo": "bar"}' myhost/foo.php
with foo.php defined as bellow will print an empty array, try it yourself if you want.
<?php
print_r($_POST);
When you need to get JSON from the body of the POST request, you need to get all the body, and then parse it from JSON.
You can do this in several ways, one of which being the one I wrote before editing.
You can also get the whole body without using any extension by using
file_get_contents('php://input')
The result should be the same.
So with the code bellow you should get what you want.
<?php
$json = json_decode(file_get_contents('php://input'), true);
print_r($json);

Categories

Resources