I am trying to have a link perform a really simple, request, but I can't seem to figure out why what I returned is "undefined".
Currently the link does a manual page request, but it's such a simple subscription thing, I want it to not refresh the page (hence the preventDefault). But if the JS doesn't work or it's blocked, the link should do a normal page request (best of both worlds?).
Here is the JS that captures the click on a link
$('#subscribe-link').click(function(e)
{
e.preventDefault();
var type = $(this).data('sub');
$.post('/includes/ajax/subscribe-article.php', { 'type':type },
function(data)
{
alert(data.result);
if (data.result == 'subscribed')
{
alert('subscribe');
}
else if (data.result == 'unsubscribed')
{
alert('unsubscribe');
}
});
});
And here is the PHP that feeds it:
if($_POST && isset($_SESSION['user_id']) && $_SESSION['user_id'] != 0)
{
if (isset($_POST['type']))
{
if ($_POST['type'] == 'subscribe')
{
echo json_encode(array("result" => "subscribed"));
return;
}
if ($_POST['type'] == 'unsubscribe')
{
echo json_encode(array("result" => "unsubscribed"));
return;
}
}
}
Now, I've checked what "data" returns by itself which is this:
{"result":"unsubscribed"}
Which is correct, I'm not sure what I'm missing this time.
As the variable data contains the JSON representation of your expected result, it is plainly a String. Yet you try and access information contained in that string as an object. For this to work, you first need to create an object from the string by decoding the returned JSON:
var myData = JSON.parse(data);
alert(myData.result);
...
You need to parse the result as JSON. IE, data_array=JSON.parse(data);
Related
I am developing a web page which displays an alert as soon as somebody inserts a new tuple in a database table using the same 'mesa' column that I sent in my AJAX request, so for that purpose I created a Javascript Timer in which I am constantly sending AJAX requests to check if there is a new tuple in my database table and so far the timed AJAX request are working, but when I want to condition the response with an if to see if the value of it equals to a certain value, it just completely skips it, so I am unable to display alerts even if the values that the AJAX response requests are throwing are right, so I was wondering what I could be doing wrong, I have been analyzing the code for over 2 hours and I don't seem to find the error, I even displayed alerts to verify that the response is equal to 0 or 1 which showed up that they do display them right, and I used response.responseText too , any help would he highly appreciated, thank you so much.
This is my Javascript file
var Solicitud_Comandas = [];
for (var k = 1; k <= 15; k++) {
Solicitud_Comandas[k] = SolicitudComanda(k);
if(!sessionStorage.getItem("rm"+k))
{
sessionStorage.setItem("rm"+k,false);
}
}
function SolicitudComanda(k)
{
return function() {
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "Consultar_Comandas_Pendientes.php",
data: {mesa : k},
complete: function (response, TextStatus)
{
MensajeAlerta(response,k);
},
fail: function (resultado,TextStatus)
{
alert("it didn't work because... " + resultado+ " " +TextStatus);
}
});
});
}
}
function MensajeAlerta(response,m)
{
if(response == 0 )
{
sessionStorage.removeItem("rm"+m);
sessionStorage.setItem("rm"+m,false);
}
else if (response == 1)
{
if(sessionStorage.getItem("rm"+m) == "false")
{
alert("Hay una comanda pendiente en la mesa "+m);
sessionStorage.removeItem("rm"+m);
sessionStorage.setItem("rm"+m, true);
}
}
}
Temporizador= setInterval(SolicitudDeComanda,2500);
function SolicitudDeComanda()
{
$(document).ready(function(){
for (var l =1; l<= 15; l++) {
Solicitud_Comandas[l]();
};
});
}
And this is the Consultar_Comandas_Pendientes.php
<?php
require "Conexion.php";
$NumeroMesa = $_POST["mesa"];
$Platillos = 0;
$filas = false;
$SelectionRows = "SELECT * FROM comandapendiente WHERE mesa = '$NumeroMesa'";
$rows = mysqli_query($con,$SelectionRows);
while($reg = mysqli_fetch_array($rows))
{
if(isset($reg["id"]))
{
$filas = true;
$Platillos++;
}
}
if ($filas == true)
{
echo true;
}
else
{
echo false;
}
mysqli_close($con);
?>
As you can see, if there is a new tuple, the AJAX response is going to be equal to either true or false which is what I question on the if statements in the Javascript code.
The first issue you have is caused by using the $.ajax({ ... complete: property and assuming the first argument to the callback is your data. But it is not, it is the request object (see documentation). Use success: instead of complete: and then you get the data as first argument to your callback function.
The second issue you have is caused by the PHP line:
echo false;
This does not echo anything, because in PHP when false needs to be converted to string, it becomes the empty string, unlike in other languages, where it becomes "0" or "false".
So you should better echo literal strings in PHP, like:
echo "1";
and
echo "0";
Also, make sure PHP does not output anything else than just that 0 or 1. Specifically check that there are no blanks, tabs, empty lines... etc, before the <?php tag or after the ?> tag. If you have several such opening and closing tags, try to join them into one PHP block.
For the same reason, make sure to save your PHP in UTF-8 without BOM. The Byte Order Mark is a three character sequence that is sometimes saved at the start of a file, in order to declare the character encoding as UTF-8. But this sequence would then also be part of the response. Most editors have an option to save with or without BOM.
Some remarks on your code
It is a bit strange to see $(document).ready(...) inside other functions. Although this works fine, it is not usually done this way. Normally there is no reason to have it inside another function. All is OK, if you use it once, at this position only:
$(document).ready(function(){
Temporizador= setInterval(SolicitudDeComanda,2500);
});
I would write false as a string when writing to local storage:
sessionStorage.setItem("rm"+k, "false");
It works fine without the quotes, but you then rely on the fact that JavaScript converts it to that string. I believe your code looks better with "false" written as a string explicitly.
Also, it seems unnecessary to call removeItem() if you are doing a setItem() right after it. setItem() overwrites any existing value with the same key.
In your tests on the response data, it would make more sense to do string comparisons, since the data returned by PHP will be string. So like:
if(response == "0")
... and add an else to catch any unexpected value (other than "0" or "1") so you are made aware of it (via alert or something).
If you have trouble with some unexpected characters preceding the value 0 or 1, and you can't get rid of those by removing the BOM and any white space in your PHP file, then there is a work-around by relaxing your test like this:
if (response.indexOf('0') !== -1)
It is also better to specify the dataType: 'text' option in your ajax call, so not to leave that to jQuery to guess.
I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression
I have been working on a peske problem the last few days. I have created an object to handle a login script. The login script is processed by a PHP script witch echo's out a json object:
{'status' : true} // could also be false
The ajax request completes everytime and I can console.log() it. The problem is in the callback function. I have tried the following allowable parameters/functions from the docs:
complete
success
.done()
In the call back I am attempting to set an object property/variable depending on the return. It does not see this assignment until the second time the script is run. I am assuming it is because something runs before the other or a scope issue?
So to clarify:
Lets say the script runs and I get back true. I then want to set the status of the object property to that instead of false. I put a console.log() inside the callback and that works everytime however the main object wont see it unless i submit it twice.
Here is the code. Any and all help is appreciated:
var loginAuth = {
form : $('form'),
status : false,
init : function() {
loginAuth.ajaxCall();
},
ajaxCall : function(loginData) {
// Get Post variables
var loginData = {
username : $('input[name=username]').val(),
password : $('input[name=password]').val()
};
// Proccess the form
$.ajax(
{
url : "http://localhost/url-where-results-are",
dataType : "json",
type : "post",
data : loginData,
}).done(function(data) {
if(typeof data != 'object')
{
$.parseJSON(data);
} else {
loginAuth.status = data;
console.log(loginAuth.status);
}
});
}
} //// END loginAuth Object ////
You have some things wrong. You only want to $.parseJson if it is an object. Furthermore, you do not need to call that as jQuery handles the parsing for you.
if(typeof data != 'object')
{
$.parseJSON(data);
} else {
loginAuth.status = data;
console.log(loginAuth.status);
}
This would be correct:
if(typeof data == 'object') {
alert(data.status);
if(data.status == true) {
loginAuth.status = true;
} else {
loginAuth.status = false;
}
} else {
console.log(data);
}
I am trying to get data from a form submit. Here is the code.
function codeSubmission() {
$("#questionCodeForm").submit(function() {
$.post("SubmitCode.php", $("#questionCodeForm").serialize()).done(function(data) {
var questionName = data.questionName,
options = data.options,
pollingStatus = data.pollingStatus,
codeExist = data.codeExist;
alert(data);
alert(data[1])
alert(questionName);
alert(options);
if(codeExist == true) {
$("#quizTitle").text("questionName");
for(rowNum=1;rowNum<=5;rowNum++) {
$("#checkbox-"+rowNum).val("Answer1");
$("#checkbox"+rowNum+"label").text("Answer"+rowNum);
}
$("#answerForm").slideDown(500);
} else if(codeExist == false) {
alert("This quiz code is invalid");
}
});
return false;
});
return false;
}
Now the problem is that I cannot get the data into the variables I want. Furthermore I think the data is being sent as a string rather than an array. Here is the output of alert(data) for debugging purposes
{"questionName":"Test","pollingStatus":"0","options": {"1":"Test7","2":"Test8","3":"Test9","4":"Test10","5":"Test11"},"codeExist":true}
Now the above output from the jsonencode seems right. However to see the problem here is the output of data[0].
{
So I think the jsonencode is returning as a string. What I want to be able to do is access the data like questionName. How do I do this? Please help if you can.
You can tell jQuery to use the "json" data-Type:
$.post('url', postData, function(returnData) {
alert(returnData.question);
}, 'json');
See documentation.
As OhGodWhy posted above, you also have to parse the json on the client side. You can do this using
obj = jQuery.parseJSON(data);
I want the data returned from an ajax post to be put into a javascript variable where I can then run an if statement checking whether that variable is equal to true. However, Firebug is telling me the variable verify is not defined. How do I write the function within the ajax post to set the data to verify correctly? Code is below.
$.post('ajax_file.php',
{
user_id: user_id,
band_term: band_term
}, function (data) {
var verify = data;
if (verify == 'true')
{
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}});
The ajax file returns true on success and false on failure.
if (mysql_query($sql) == true)
{ echo 'true';} else {echo 'false';}
Firebug shows me that the ajax file is returning with the string true, so I know the ajax file is working.
The issue is on a few places.
First, how you output data on you .php file. You should be returning JSON and accepting JSON on you ajax request. Look at this example:
<?php
$variable = array("stat" => true, "data" => array(10, 10));
print_r(JSON_Encode($variable));
?>
That will output this:
{"stat":true,"data":[10,10]}
Then on yout JS you'd do:
$.post('ajax_file.php', {
user_id: user_id,
band_term: band_term
}, function (data) {
//Data is the whole object that was on the response. Since it's a JSON string, you need to parse it back to an object.
data = JSON.parse(data);
if (data.stat === true){
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}
});
It's because verify was created in the callback function. Also, that variable isn't visible outside that function.
To operate on returned data from an AJAX call, do it in the callback function.
$.post('ajax.php', {
user_id: user_id,
term: term
}, function (data) {
var verify = data; //assuming data is just true or false
if (verify === 'true') {
unnecessary code
}
});
The variable is defined inside the callback function is does not match the scope of the document.
To make it actually work, just define it anywhere in the beginning of your script as follows:
var verify;
$.post('ajax.php',
{
user_id: user_id,
term: term
},
function (data)
{
verify = data; // then also remove the word var from your code here.
if (verify == 'true')
{unnecessary code}
}
);
-i wouldn not use j query for ajax ( i find getdata to be better but the call back variable needs to be passed to the next function
ie. if you are gonna alert(data) as your call back, do your if statements there.
also i was running into similar problems. using numbers such as one or zero in my php response helped alot, and i just used js to determine what the actual string or alert output would be