JSON file not changing - php

I am using a jQuery ajax function and PHP file to change a JSON file but the file will not change even though I get the "Thanks!" alert. My jQuery, PHP, and JSON code is as follows.
jQuery file:
$.ajax({
url: 'savePoll.php',
type : 'POST',
async: false,
data: 0,
success: function () {alert("Thanks!"); },
failure: function() {alert("Error!");}
})
PHP File:
$jsonString = file_get_contents('poll.json');
$data = json_decode($jsonString, true);
$data["answers"][$_POST]++;
$newJsonString = json_encode($data);
file_put_contents('poll.json', $newJsonString);
JSON File:
{
"answers":[0,0,0,0,0]
}
My JSON file never changes but yet I still get my success alert. Thanks for any help.

This: $data["answers"][$_POST]++; doesn't look valid.
The failure: function will only trigger on a non 200 HTTP response.
The error in #1 is not serious enough to trigger an HTTP error. You would have to implement logic to make the page return a 400-level HTTP response code in order to ever have failure: trigger.

Make sure the file the you want to change has 755 for its permission.

Related

Send back response string to use in jQuery's ajax function

I have a function for making a post request.
$('#save').click( function() {
...
$.ajax({
type: 'POST',
url: 'logic/save.php',
data: { 'json': JSON.stringify( post ) },
dataType: 'jsonp',
success: function( data ) {
console.log('success!')
}
});
}
The request handler is written in php, as you can see, and performs operations with mysql. Because of my poor knowledge of php and requests, I do not see any success! output in the console. Php code runs fine, and the mysql queries runs with no errors.
What I want is to be able to write something in php code at the end so that my code in js could receive it as a positive response (like 200, OK) and the success! line in the console will then (I believe) appears.
What code should I add to the php file?
UPDATE: since many of people requested the php code, here's the link to it. Thank you for fast replies, guys.
First, you should switch from jsonp to json, as you have no need for jsonp in this case. The following instructions assume you have made that change.
The bug is in your PHP code when you respond back to the client. You do so with this line:
print_r( "New item inserted.\n" );
However, jQuery is expecting you to be returning JSON back from your endpoint (and, truthfully, it should, because sending back plaintext to an ajax client is almost never the right way). We can make this work with jQuery by changing the line above to something like this:
print json_encode( array('success' => true, 'message' => "New item inserted." ) );
You should find yourself in the success callback in your client. This code would work for your success handler:
{ // ...,
success: function(response) {
if (response.success) {
alert(response.message);
}
}
}
You'll probably want to use something other than an alert, though. But that's up to you.

trouble with json response from php in jQuery.ajax call

I am using $.ajax to get a JSON response from a php script. if i log the data variable from the $.ajax success function it outputs a properly formatted JSON object, however when I try to access properties of the data var it's undefined. here is the php the is being sent back:
echo json_encode(array("status"=>true, "success"=>"Login Success", "message"=>"You have been logged in successfully."));
and here is my ajax call:
$.ajax({
type: "POST",
data: {
login: true,
username: $('#login-username').val(),
password: $('#login-password').val()
},
async: false,
url: "./php/client-login.php",
success: function (data) {
console.log(data.status);
if (data.status) {
console.log(data.success);
displayModal(data.success, data.message, "./js/login-modal-code.js");
} else if (!data.status) {
displayModal(data.error, data.message, "./js/login-modal-code.js");
}
},
error: function (jqXHR, status, responseText) {
console.log(status);
}
});
if i add the dataType: "json" option to the $.ajax call I get a parse error and if i try to do $.parseJSON(data); to access the data in the data var I get and unexpected token error. I'm not really sure what I'm doing wrong, I've used this setup before and it always has worked before but for some reason it isn't now. anyone see where i've gone wrong?
EDIT: forgot to mention here is the response from the php script:
{"status":true,"success":"Login Success","message":"You have been logged in successfully."}
EDIT 2: Here is a screen of my console. the top .length call is the json that was logged from console.log(data) and the bottom one is from the response in chrome dev tools network tab for the response from the php script. they line up perfectly yet the second is showing a length of 93, how can i fix this?
I was reading on jQuery Docs and found that "dataType: jsonp" does not work with sync request, and you're making this kind of request since you have async: false. Turning it on may solve your problem.
Also, give a look at the docs.
Good luck!
So I figured out a workaround for this problem, first I did JSON.stringify on the data followed by JSON.parse and lastly $.parseJSON() to get a javascript object to work with. Not sure why there are 2 invisible characters being added between when it leaves the php script and reaches the $.ajax call so if anyone knows why let me know

JSON error(s) with php backend

I've never worked with JSON before and it's not going well...
I have a PHP script that returns a JSON array(is that the correct term?)
The script returns:
{"items":1000,"mitems":0,"donations":0,"total":1000}
NOTE: The script also sets the Content-Type to application/json
Here is my front-end javascript to handle that response:
function ajax(){
$.ajax({
url: '../ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function( data ){
// data.responseText is what you want to display, that's your error.
alert(data.responseText);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
When that function is called I get an alert with the following message:
{"items":1000,"mitems":0,"donations":0,"total":1000}
If everything was successful, I should get an alert that says success, right?
Can someone please tell me what is going on here?
Thank you!
This is the least documented thing in jquery what you need to do is alert the actual error in order to debug it. so do the following:
function my_ajax(){
$.ajax({
url: '/ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function(jqXHR, textStatus, errorThrown){
// data.responseText is what you want to display, that's your error.
alert(jqXHR+","+textStatus+","+errorThrown);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
So two things I've done:
Change the name of the function (ajax is kinda a bad name :S) and improved the error reporting.
You should be getting the alert "success" yes. So something is going wrong.
EDIT:
Just noticed another thing, I dont think "../" would be a great way to reference the url, usually its either "/foo/ajax" which will allow you to use this function on any page.
It could be that your PHP script returns an error status code and even though it prints out the correct result, it still fails. I tested your scripts on my system and I got the 'success' alert. Then I changed my PHP script to the following:
<?php
header('Content-type: application/json', true, 401);
echo '{"items":1000,"mitems":0,"donations":0,"total":1000}';
?>
Note that the third parameter of the header function sets the http response code to 401 - Even though the correct output is sent back to the client; officially, the request has failed because of that status code. After running this code, I got the exact same problem as you.
So in summary, there might be something in your script which is causing a non-fatal error which doesn't show in the output of the script.
Are you defining the MIME type in your HTTP response?
Try adding a Content-type header to the output of your script.
<?php
...
$output = json_encode(...);
header('Content-type: application/json');
echo $output;
...
?>
You can also try using the mimeType parameter in your $.ajax() call to override the response type.
http://api.jquery.com/jQuery.ajax
Are you running your PHP scripts under Apache or on their own (chmod u+x on the script)? You probably need to use a PHP framework such as Zend, CodeIgniter or CakePHP and define a controller action that handles your AJAX request to have a proper HTTP response.
As the guy above me said, you should be using the json_encode(); function in PHP then echo'ing that output.
Make sure you encode an array though:
<?
$send = array(
'items' => '1000',
'mitems' => '0',
'donations' => '0',
'total' => '1000',
);
echo json_encode($send);
?>

Can I return an output status from a JQuery AJAX request with PHP?

I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
alert(output);
}
});
However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.
I tried the error option:
...
success: function(output){
alert(output);
},
error: function(output){
// do something
}
but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.
In pseudo-code, I'm looking for something like this:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
if(output.status == 0){
alert(output);
}else{
// do something else
}
}
});
Is anything of the sort possible? Thanks for any and all help!
I usually return data from the server in JSON format. This way I can return as many different types of data as may be needed by the success function in javascript.
basically in PHP you would do something like
$response = new stdClass();
$response->error = 'Could not connect to Mysql';
$response->message = 'Some other text';
echo json_encode($response);
in JQuery, the ajax() method would automatically detect that the response is json and parse it into a javascript object, so you could access like this
if (typeof response.error !== undefined) alert(response.error);
for more on that look at dataType argument for the ajax() method in the jQuery documentation.
Yes. You can use HTTP status codes:
header('HTTP/1.1 500 Internal Server Error');
And use jQuery's statusCode property for jQuery.ajax():
$.ajax({
// stuff
statusCode: {
500: function(data) {
alert('Something went wrong!');
}
}
});
If your needs extend beyond what HTTP can offer, you can just return a status code within your data and process it in the success function, switching on data.status.
If I haven't misunderstood your question...
What I usually do is set the datatype of the AJAX call to 'xml' and output an xml from my PHP script. So I get multiple values in result. I usually make these attribute values.
<result status="success" something="etc" />
// vs.
<result status="failure" error="1" />
// consider 1 as the DB error
With this approach you might need to use the # tags in some PHP functions to prevent outputting the default errors.

PHP script returns error/nothing when fetching data with AJAX

I have a PHP file called 'myProxy.php' sitting on my server that looks like this:
<?php
echo "text";
exit();
?>
When I try to get that string from the file with an AJAX call that looks like this:
$.ajax({
url: "http://www.mydomain.com/myProxy.php",
type: "GET",
success: function(data) {
alert("Horray!");
}
});
The script turns absolutely nothing and I get a red error icon in the Firebug console. Does anyone know what might be causing this? Perhaps a setting is not set somewhere?
I have a feeling you're running into a same origin policy restriction.
For plain old AJAX, your script and resource should exist on the same domain. If this is actually the case, you can simply use
$.get("/myProxy.php", function(data) {
alert("Hooray!");
}, "text");
If you truly need cross-domain support, you can change your PHP script to respond to JSONP requests
<?php
// myProxy.php
$callback = isset($_GET['callback']) ? $_GET['callback'] : 'callback';
$data = array('text' => 'text');
header('Content-type: text/javascript');
printf('%s(%s)', $callback, json_encode($data));
... and the JavaScript
$.getJSON("http://www.domain.com/myProxy.php?callback=?", function(data) {
alert(data.text);
});
Same origin policy.
You can't place your script on another domain/subdomain/protocol than your current script is

Categories