Passing object values from php to jQuery - php

I am using jQuery .ajax() to submit some values to db.php page where I retrieve additional records from my db. I use a class that returns the query results in a form of an object. I need to return that object back to original page in response and output it.
$.ajax({
type: 'POST',
url: '/db.php',
data: {
'item': myItem
},
dataType : 'json',
async: true,
success: function (response) {
// need returned values here
}
});
db.php
$results = $db->get_results("
SELECT *
FROM t1
WHERE id = " . $id );
// if I were to output my results here I'd do
// foreach ($results AS $res) {
// $item = $res->item;
// }
echo '{ "res": '.$results.' }';
Now sure if I need to encode anything before passing it back to my JS...

how about json_encode()
echo json_encode($result);
js:
success: function (response) {
console.log(response)
for(var i=0; i <response.length; i++){...}
}
edit: make sure you add application/json; charset=utf-8 header, if not you'll need to parse the response JSON.parse(response)

you can do something like this with the result:
echo json_encode(array(
'result' => $result,
));
and in your success: function(response)
success: function(response){
response = JSON.parse(response);
console.log(response);
}

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.

Jquery ajax POST response is null

I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);

Passing Looped Array Values From PHP to JavaScript & JQuery

I am trying to make a search box in my web application, and I used ajax post to make a request to my server. My question is:
Is it possible to send looped array values from PHP to my JavaScript?
I want to get all of the results from my server.
CLIENT SIDE: Ajax POST request
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
type: "POST",
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
// Get the search result
}
});
});
</script>
SERVER SIDE (after retrieving the post from ajax, and making queries):
while ($result = mysql_fetch_assoc ($query))
{
$resultName = $result['name'];
$resultAddress = $result['address'];
}
$results = array();
while ($result = mysql_fetch_assoc ($query)) {
$results[] = $result;
}
echo json_encode(array('results' => $results));
In your success callback you can then iterate over result.results which contains an object with the column names from your query as attributes.
success: function(result) {
$.each(results, function(i, row) {
console.log(row.name, row.address);
})
}
It is also advisable to use dataType: 'json' in your $.ajax({...}); arguments to avoid unnecessary guessing of the response type.
In case you have more columns in the SQL resultset than you want to forward to the client, you could add a custom array in the loop:
$results[] = array('name' => $row['name'], 'address' => $row['address']);
yes you can you can return a json string :
$.ajax({
type: "POST",
dataType: 'json', // return type is json ;
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
$.each($result,function(index, value){
// use params
}
}
});
and on your php side you use json_encode()

jQuery json from PHP result

I have this jQuery script
var dataString = "class_id="+class_id;
$.ajax({
type: "POST",
url: "page.php",
data: dataString,
success: function (msg) {
//stuck here
},
error: function () {
showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
}
});
my PHP output is something like this
echo '{status:1,message:"Success"}';
or
echo '{status:0,message:"Failure"}';
what I am trying to do in jQuery success: function(...) part is check if status is 0 or 1 and then show the message.
I tried to do is
success: function(text) {
if(parseInt(text.status) == 1) {
alert(text.message); // this is the success, the status is 1
} else {
alert(text.message); // this is the failure since the status is not 1
}
}
which didn't work, it was only outputing the else statement, even though the status was 1
Your PHP is generating invalid JSON, and shows no sign of setting an appropriate content type header to tell the browser to treat it as JSON in the first place. So first, fix the PHP:
header('application/json');
echo json_encode(Array("status" => 1, "message" => "Success"));
Then:
success: function (msg) {
alert(msg.message)
},
You can also use
PHP
echo json_encode(Array("status" => 1, "message" => "Success"));
JS
Inside your call back function use
success: function (msg) {
$.parseJSON(msg);
alert(msg.message);
}
The parseJSON will convert the json string returned/echoed by PHP in to json object.
Try something like below,
$.ajax({
type: "POST",
url: "page.php",
data: dataString,
dataType: 'json',
success: function (msg) {
if (msg.status == 0) {
alert("Success " + msg.message);
} else if (msg.status == 1) {
alert("Error " + msg.message);
}
},
error: function () {
showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
}
});
If you don't specify in $.ajax the type 'json' data passed to response handler is treated as string. While if you specify 'json' dataType parameter you can use:
msg.status
and
msg.message
As a hint i suggest in php to use the json_encode function to generate json output.

JQuery + Json - first steps with an example

I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";

Categories