How to convert stringified data to an object? - php

My php has header('Content-type: application/json') and a json_encode.
The ajax code I use to send the data to the php file has dataType: 'json' and I am sending the data as a string (json.stringify).
The problem is, I can't make $_POST['data'] work on a string.
Any way to convert it to an object?
edit: What I am trying to achieve is, sending data from ajax to php where a query looks up the information from the database and the php file sends an array using JSON to the ajax and the ajax displays it.
Ajax:
function op_prof(obj) {
var xval = obj.id;
$.ajax({
type: "POST",
url: '../script/profile.php',
dataType: 'json',
data: JSON.stringify({'u_search':'xval'}),
cache: false,
success: function(data) {
console.log(data);
alert(data);
alert({u_search:xval}['u_search']);
$("#co_profile").html(data).show();
}
});
};
PHP:
<?php include(dirname(__FILE__). '/../script/config.php');
session_start();
$id = $_POST['u_search'];
foreach($pdo->query("SELECT * FROM Users WHERE ID='$id'") as $row) {
$fullname = $row['FullName'];
$data = array("u_data"=> true,"inpt"=>"<p>My name is " . $fullname . "</p>");
header('Content-type: application/json');
echo json_encode($data);
?>
<?php $pdo = null; ?>
I'd also like to know any other way of achieving this (even without using JSON)

Try json_decode("php://input");

Related

Ajax Post to PHP returning empty array

I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.
Ajax request in 'adopt.php':
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {'info': info},
success: function(data){
console.log(data);
}
});
ajax.php code:
if(isset($_POST['info'])){
$_SESSION['array'] = $_POST['info'];
}
back in adopt.php, later:
if(isset($_SESSION['array'])){
$arr = $_SESSION['array'];
echo "console.log('information: ' + $arr);";
}
in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)
Try below code i think you miss return ajax response
adopt.php
<script>
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {info: info},
success: function(data){
console.log(data);
}
});
</script>
ajax.php
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(["result" => "success"]);
}
To get the response data from PHP, you need to echo your data to return it to the browser.
In your ajax.php:
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(['result' => $_SESSION['array']]);
}
Your ajax.php is not returning any data.To get data at the time of success you need to echo the data you want to display on success of your ajax.

Creating a json file by PHP

I want to update the json file by overwriting the old one. I can export the data to a json string by using some jquery. And the data is stored in the variable json_update . But I don't know how to send the data to php.
$(function () {
$('#switcher').click(function () {
var json_update = JSON.stringify($('#table-hover').bootstrapTable('getData'));
$.ajax({
type: "POST",
url: "adding2.php",
data: json_update,
contentType: "application/json; charset=utf-8"
dataType: "json",
success: function (data) {
alert("success");
}
});
});
});
And here is the adding2.php . Thanks for helping me.
<?php
$data = $_POST['json_update'];
$fileHandler = fopen('work2.json', 'w+');
fwrite('work2.json',$data);
fclose($fileHandler);
?>
Give the data a parameter name before sending it:
var json_update = { json_update: JSON.stringify($('#table-hover').bootstrapTable('getData')) };
This will make it accessible in $_POST['json_update']
The data you send from the client side (the value of json_update) is stored in $_POST, so just change $data = $_POST['json_update']; to $data = $_POST;.

JSON Padding With PHP

Please can anyone assist I'm trying to get my JSON data displayed on my html5 localhost page,
I'm still new to JSON
I get the following returned but no data is loading on the page.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
Please if anyone can assist.
Below is my php script
`mysql_select_db($database_xxx, $xxx);
$rsfet = "SELECT * FROM cs_tracking ";
$fet = mysql_query($rsfet, $xxx) or die(mysql_error());
$json = array();
while($r=mysql_fetch_array($fet)){
$json[] = $r;
}
header('Access-Control-Allow-Origin: *');
echo $callback ='('.json_encode($json).')';`
and my javascript to display the table data
`
$(document).ready(function(){
$.ajax({
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: true,
success: function(data){
$.each(data,function(i,photo){
var tblRow =""
+""+data.CS_Track_Child+""
+""+data.CS_Track_Date+""
+""+data.Tracking_Status+""
+""+data.CS_Tracking_ID+""
+"" ;
$(tblRow).appendTo("#userdata tbody");
});
},
});
});`
The $callback variable is not magically declared in your script (at least, it shouldn't be); you can access the value via $_GET['callback'] but make sure to sanitize its value:
if (isset($_GET['callback']) && preg_match('/[A-Z]\w*/i', $_GET['callback']) {
header('Content-Type: application/javascript');
header('Access-Control-Allow-Origin: *');
printf('%s(%s);', $_GET['callback'], json_encode($json));
}
You have two GET parameter of callback one is valid but empty and second is invalid.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
So remove your parameter and try with this:
url: 'http://xxxxxxxxxxx.com/getCheck.php',

echo json_encode() not working via ajax call

I really don't know what i'm missing here. I have this script:
<script type="text/javascript">
function ServiceOffer(){
var service_name = $('#service_name').val(),
dataString = "service=" + service_name;
$.ajax({
type: "POST",
url: "posted.php",
data:dataString,
success:function(data){
console.log(data);
}
});
}
$(document).ready(function(){
ServiceOffer();
$(document).on('change','#service_name',function(){
ServiceOffer();
});
});
</script>
And here is my code for posted.php
<?php
$connect = mysql_connect('localhost','root','') or die('Unable to connect'.mysql_error());
$select = mysql_select_db('hcs',$connect) or die('Unable to select database'.mysql_error());
$service = $_POST['service'];
$query = mysql_query("SELECT * FROM serviceoffer WHERE servicename = '$service'");
$num = mysql_num_rows($query);
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}
echo json_encode($data);
So what i'm missing? I don't think there is a string that is being attached in my code and it gives me string in my console and not json encoded data. Please Help! Thanks!
Edit: Here is the data that is being returned in my console.
You have three options:
Add dataType: 'json' to the options in $.ajax.
Add header("Content-type: application/json"); to the PHP code.
Use console.log($.parseJSON(data)) in the success function.
Note that you shouldn't use option 3 if you've also used options 1 or 2. jQuery automatically parses the JSON in the first two cases, and you'll try to parse the result of that, which won't work.
At a minimum, you should send the appropriate header in PHP, eg
header('Content-type: application/json');
echo json_encode($data);
exit;
You can also set the dataType in jQuery's $.ajax method to specify the expected response type. I also find it easier to send request parameters as object literals (saves having to build URL encoded strings), eg
$.ajax({
type: 'POST',
dataType: 'json',
data: { service: service_name },
//etc
Update
As shirejedi mentioned, you should initialise $data as an array
$data = array();
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}

Print JSON Data Individually

I have an AJAX Request, that essentially queries a database then posts the data back to the JS, however I can't print individual bits of data.
My code is as follows:
$.ajax({
type: 'POST',
url: '_process/offerrespres.php',
dataType: 'json',
data: {
msgid: msgid,
usrid: usrid
},
success: function(){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}
});
The PHP:
<?php
include_once 'connect.php';
if ($_POST) {
$msgid = mysql_escape_string($_POST['msgid']);
$usrid = mysql_escape_string($_POST['usrid']);
$getmsgq = mysql_query("SELECT * FROM booking_requests WHERE receiver_id = '$usrid' AND msg_id = '$msgid'");
$getmsg_info = mysql_fetch_array($getmsgq);
$data['success'] = true;
$data['date_sent'] = $getmsg_info['date_sent'];
$data['pro_name'] = $getmsg_info['pro_name'];
$data['accept_decline'] = $getmsg_info['accept_decline'];
}
header("Content-Type: application/json", true);
echo json_encode($data);
mysql_close();
?>
As you can see I've tried this:
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
the error in the console says "data not defined". The output from the PHP file is correct and how it should be, I just can't print one single piece of data.
Your callback function isn't accepting the return data as an argument
The line that reads success: function(){ should be success: function(data){
Also, the true isn't needed in your call to header("Content-Type: application/json", true);. The default action of this function is to replace headers, so true is already implied. That argument is only necessary if you don't want to replace the previous Content-Type. Makes no difference to your code, just a tip.
You didn't specify the data variable in the success function.
It should be:
success: function(data){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}

Categories