I'm trying to get a json object from php so I can work with it in ajax. Here is my ajax code:
$.ajax({
type: 'get',
url: eventsListPath,
dataType : "json",
data: {},
success: function (data) {
$('#eventInformation').html(data.table);
alert(data.table);
}
});
And my PHP:
$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);
But the line
alert(data.table);
comes back with 'undefined'. Any ideas?
Try this in your php code. Json encode an array.
$obj['table']="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);
Alternate - Or your class should be like this
class your_classname
{
public $table;
//other class related code
}
$obj = new your_classname;
$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);
if I'm not mistaken, json_encode just works for arrays
$obj = [{table:"hey"}];
<?php
$obj = new stdClass();
$obj->table="hey";
echo json_encode($obj)
produces
{"table":"hey"}
Check it using Firebug. Also check the content-type, should be Content-Type: application/json
you must pass array to json_encode not object
<?php
$array['table'] = "hey";
echo json_encode($array, JSON_UNESCAPED_SLASHES);
Related
So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support
I am sending a JSON object from js to post.php
$.ajax({
type:'post',
url:'post.php',
data:{jsonobject:json_str}
});
but I am not able to retrieve the result in a post.php file
$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;
function jsonString2Obj($str){
return json_decode(stripcslashes($str));
}
I have no idea about your $jsonr_str.
It's my example:
$json = '{"people":[{"user":"Amy"},{"user":"Lee"},{"user":"David"}]}';
// covert into object
$data = json_decode(stripcslashes($json));
echo "People[0]=" . $data->people[0]->user;
// or covert info array
$data = json_decode($json, true);
// Using print_r()
echo "<pre>" .print_r($data, true). "</pre>";
Try like this
var data = {
people:{user:'Joe Cooper'}
};
$.ajax({
type:'post',
url:'post.php',
data:{jsonobject:JSON.stringify(data)}
});
<?php
$obj = jsonString2Obj($_POST['jsonobject']);
echo $obj->people->user;
function jsonString2Obj($str){
return json_decode(stripcslashes($str));
}
here is my simple code
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
success:function(response){
$('#getcart').html(response);//want to display $return_value (from action page)
$('#getcart2').html(response);//want to display $return_value2 (from action page)
}
});
Here i am sending request to action.php
and if in action.php i have echo two variables separately for example.
$return_value = " //Some html here "; echo $return_value;
$return_value2= "//some other html"; echo $return_value2;
So the question is in ajax i have function with argument response . how i will be able to receive these both variables from php and display it in different divs.
i hope you guys help me. thanks.
Send the responses as JSON.
In PHP
$return = array( $return_value, $return_value2 );
echo json_encode($return);
In Javascript
var response = JSON.parse(response);
$("#getcart").html(response[0]);
$("#getcart2").html(response[1]);
your could return a json from action
echo json_encode(array('cart' => $return_value, 'cart2' => $return_value2));
then in your js,
$.ajax({
url:'action.php',
method: 'POST',
data:{getcart:1},
dataType: 'json',
success:function(response){
$('#getcart').html(response.cart1);//want to display $return_value (from action page)
$('#getcart2').html(response.cart2);//want to display $return_value2 (from action page)
}
});
You need to use json_encode in order to get multiple records or data.
action.php
<?php
header('Content-Type: application/json');
$array = array(
'var1'=> 'var value 1',
'var2'=> 'var value 2'
// more variables to go
);
echo json_encode($array);
?>
and then read your variables in JS
dataType: 'json',
success:function(response){
console.log(response.var1);
console.log(response.var2);
$('#getcart').html(response.var1);
$('#getcart2').html(response.var2);
}
You can use json_encode to create an object like:
$array = [
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
];
echo json_encode($array)
Then add dataType: 'json' to your ajax options. The response then will be an object like:
{
"return_value" => " //Some html here ",
"return_value2" => "//some other html",
}
Where you can access the specific values with e.g. response.return_value2 and thus separate them.
Here i am passing the javascript array values to php using the jquery ajax.now i want to recive the data in php script. how should i do it?
php:
<?php
$list = array
(
//here i want to get the ajax array data
);
$t = time();
$file = fopen("xls/$t-userinput-input.csv","w");
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file); ?>
Jquery:
function arrayPush(val1,val2) {
uservalues.push(val1,val2);
passvalues()
}
function passvalues(){
$.ajax({
type: "POST",
data: {info:uservalues},
url: "write.php",
success: function(msg){
alert("Thankyou")
}
});
}
Because you're POSTing the data, just try with:
$list = $_POST['info'];
First of all, read it from PHP POST variable:
$jsonRawData = $_POST['info']
Next, decode it to have php array - http://php.net/manual/en/function.json-decode.php
$decoded = json_decode($jsonRawData);
You can always peek what's inside PHP variable with var_dump.
i cant seem to get this to work, i'm trying to send a variable to php so it can write it to file but its just not working..
var jsonString = JSON.stringify(vars);
$.ajax({
type: "POST",
url: "woepanel.php",
data: {data : jsonString},
cache: false,
success: function(){
$('#sent').attr("bgcolor", "#00FF00");
$('#notsent').attr("bgcolor", "#FFFFFF");
}
});
it seems to be sending ok because the success works but php wont pick it up
<?php
$vars=json_decode($_POST['jsondata']);
?>
<?php
$fp = fopen('vars.txt', 'w');
fwrite($fp, $_POST["jsondata"]);
fclose($fp);
?>
Try this code:
<?php
$vars=json_decode($_POST['data']);
$string_data = serialize($vars);
file_put_contents('vars.txt', $string_data);
?>
you have this
data: {data : jsonString}
in your ajax call which means you should use
$_POST['data']
to extract the value