Getting a JSON object from javascript to php - javascript

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));
}

Related

PHP array to seperate JavaScript file via AJAX

I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.
Can you please explain what am i doing wrong?
My php file: get.php
<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
array_push($x_array, $row["x"]);
array_push($y_array, $row["y"]);
}
} else {
echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>
And this is my JS file:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "get.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON(data); // parse the answer
x = eval(x);
console.log(x.length);
}
});
});
I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...
You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.
You should make each array an element of a containing array, which you then return as JSON.
$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);
Then in the jQuery code you would use:
var x = data.x;
var y = data.y;
Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().

How to read javascript array values php

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.

Use Data From PHP in JavaScript VIA Ajax

I am learning PDO'S. I have a simple program that retrieves on button click all users in an SQL table and encodes them into JSON. It then returns this data and is retrieved via AJAX. I alert out the data and it is in Array format. I want to know how I can actually access these values, nothing I tried work. The table columns are "name" , "message" and "posted" if that helps.
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'Get/index.php',
success: function(data) {
// var obj = $.parseJSON(data);
// var v = data.name;
}
});
<?php
//print_r(PDO::getAvailableDrivers());
//create handler of new PDO object with parameters of sql
//details, username and password_hash
try {
$handler = new PDO('mysql:host=127.0.0.1;dbname=app','root','');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
//die("Sorry Database Issue");
echo $e->getMessage();
die();
}
$query = $handler->query('SELECT * FROM guestbook ');
query->execute();
$results=query->fetchAll(PDO::FETCH_ASSOC);
// save the JSON encoded array
print json_encode($results);
return $results;
?>
Cleaned & updated the code and added jquery json:
$("button").click(function(){
$.getJSON('Get/index.php', function( data ) {
$.each( data, function( key, entry ) {
var v = entry.name;
// and so on
});
});
});
<?php
try {
$handler = new PDO('mysql:host=127.0.0.1;dbname=app','root','');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$query = $handler->query('SELECT * FROM guestbook ');
query->execute();
$results=query->fetchAll(PDO::FETCH_ASSOC);
// save the JSON encoded array
echo json_encode($results);
?>

Returning json data from php to ajax

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);

Always get empty result when call a ajax in my jquery

i'm creating a plugin for WooCommerce
in my plugin php file when i call a php file with jquery ajax i get empty result
this is my ajax code:
jQuery(function() {
jQuery.ajax({
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
success: function(output) {
alert(output);
}
});
});
and this is my php file:
<?php
$output = 'test';
return $output;
?>
You should change this:
<?php
$output = 'test';
return $output;
?>
To this:
<?php
$output = 'test';
die($output); // or echo or print
?>
Returning a variable will not return it as a response to an ajax call.
try this
<?php
$output = 'test';
echo $output;
?>
You can try this:
create a empty variable and insert your data to this.
var response = '';
$.ajax({ type: "GET",
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
async: false,
success : function(text)
{
response = text;
}
return response;
});

Categories