jQuery json from PHP result - php

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.

Related

Scripts returning double spaces to xhr request (ajax)

Something strange is happening since I moved my webserver to a new machine.
Now whenever an ajax call completes and nothing is returned, the data variable contains two spaces.
I have:
$.ajax({
url: 'http://192.168.0.6/access/login',
data: 'user='+user+'&pass='+pass+'&rem='+remember,
type: 'POST',
success: function(data)
{
alert(data.length)
if(data)
{
$('#errorMessage').html(data) ;
$('#loginWarn').fadeIn() ;
} else {
window.location = 'login'
}
}
})
On success my PHP script returns 0, indicating success and nothing is returned so the user is redirected to 'login'.
However, since the move 'data' is now a variable of length two (tested with data.length).
Does anyone know what is wrong?
Try this
$.ajax({
url: 'http://192.168.0.6/access/login',
data: '{ "user":"' + user+ '",pass":"' + pass+ '",rem":"' + remember+ '"}',
type: 'POST',
success: function(data)
{
alert(data.length)
if(data=="true")
{
$('#errorMessage').html(data) ;
$('#loginWarn').fadeIn() ;
} else {
window.location = 'login'
}
}
})

ajax not properly parsing the value returned by php

I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});

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

Why won't my .ajax request work?

The code I want to work:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
dataType: "json",
processData: false,
success: function(html) {
$("#srchFrm").append(html);}
});
The code that works:
$.ajax({
type: "POST",
url: "_Source/ajap/ajap.nlSrch.php",
data: { sndJson : jsonData },
success: function(html) {
$("#srchFrm").append(html);}
});
Unfortunately when I send the first one my post data looks like this "Array ()" and when I use the later I get this "Array ( [sndJson] => [\"8\",\"3\",\"6\",\"7\"] )".
I know that there has to be a simple explanation but I haven't been able to figure it out.
Help please!
Try sending your data in a query string...
$.ajax({
type:"POST",
url:"_Source/ajap/ajap.nlSrch.php?json="+jsonData,
dataType:"json",
success: function(data) {
$("#srchFrm").append(data);}
error: function(xhr, ajaxOptions, thrownError)
{alert("Error!");}
});
You can use shorthand $.post instead of using low level ajax class --- because you don't need to advanced handling. So, this one will be great enough.
$(document.ready(function(){
$("#submit_button").click(function(){
$.post('php_script.php', {
// here's what you want to send
// important -- double quotes, 'cause It's evals as valid JSON
"var1" : "val1"
"var2" : "val2"
}, function (respond){
try {
var respond = JSON.parse(respond);
} catch(e){
//error - respond wasn't JSON
}
});
});
});
PHP code:
<?php
/**
* Here you can handle variable or array you got from JavaScript
* and send back if need.
*/
print_r($_POST); // var1 = val1, var2 = val2
?>
Back to your question,
Why my .ajax request doesn't work?
This is because JavaScript throws fatal error and stops further code execution.
You can catch and determine the error occasion, simply by adding
try {} catch(){} block to the statement you think may occur any error
When you specify dataType: json, jQuery will automatically evaluate the response and return a Javascript object, in this case an array. You're taking the result and adding it as html to #srchForm, so it does not make sense to convert it to a javascript object. Use dataType: html, or none at all.
http://api.jquery.com/jQuery.ajax/
The following examples above are not reusable. I am a huge fan of reuseable code. here is my solution.
Software design 101:
DRY Don't repeat your self. You should wrap your code into an object. This way you can call it from anywhere.
var Request = {
version: 1.0, //not needed but i like versioning things
xproxy: function(type, url, data, callback, timeout, headers, contentType)
{
if (!timeout || timeout <= 0) { timeout = 15000; }
$.ajax(
{
url: url,
type: type,
data: data,
timeout: timeout,
contentType: contentType,
success:function(data)
{
if (callback != undefined) { callback(data); }
},
error:function(data)
{
if (callback != undefined) { callback(data); }
},
beforeSend: function(xhr)
{
//headers is a list with two items
if(headers)
{
xhr.setRequestHeader('secret-key', headers[0]);
xhr.setRequestHeader('api-key', headers[1]);
}
}
});
}
};
Usage:
<script type="text/javascript">
var contentType = "applicaiton/json";
var url = "http://api.lastfm.com/get/data/";
var timeout = 1000*5; //five seconds
var requestType = "POST"; //GET, POST, DELETE, PUT
var header = [];
header.push("unique-guid");
header.push("23903820983");
var data = "{\"username\":\"james\"}"; //you should really deserialize this w/ a function
function callback(data)
{
//do logic here
}
Request.xproxy(requestType, url, data, callback, timeout, header, contentType);
</script>

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