Using AJAX to call a php function keeps failing - javascript

im having a problem trying to get an ajax call to trigger a php function and then return successfully. As far as i can see my syntax is correct.
But all i get back is failed! Any ideas?
EDIT
I have changed my AJAX request to send without using data, just to rule out that being a problem and i have implemented some of the things people suggested below but to no avail, heres what my 2 files look like now:
ship.js:
function set_ship()
{
//var datastring = {'ship':'true'};
$.ajax({
type:'POST',
url:'soap/classes/class.ship.php',
success: function(success){
alert('success');
},
error: function(fail){
console.log(fail);
}
});
}
And my PHP class.ship.php:
<?php
var_dump("hello");
header('Content-type: application/json');
echo json_encode(array("result"=>"true"));
From the var_dump on my PHP script i can see that the class.ship.php isnt even being called for some reason.
Thanks

Please try this
json_encode(array("result"=>"true"));
because
json_encode(true) // will return just "true" which is not a valid json
Also try serializing the dataString , by doing
data: datastring.serialize();

lowercase JSON_ENCODE
success: function(success), error: function(fail)
check what is returned in network tab of firebug.

You need to set the content header to json header('Content-type: application/json'); and make sure you request return only json coz ajax is waiting only for "JSON" and it will throw parse error
if(isset($_POST['ship']) && $_POST['ship'] == "true"){
$result = "result";
header('Content-type: application/json');
echo json_encode(true);
}

I would suggest that you check what it being actually returned by the server.
The error callback receives one argument representing the xhr object, so you can inspect that directly by placing a breakpoint or using console logging, like this
error: function(xhr) {
console.log(xhr);
}
Likewise, the success callback receives three parameters: the status, the returned data and the XMLHTTPRequest Object, so you can check those in the very same way:
success: function(status, data, xhr) {
console.log(status, data, xhr);
}
You should look for the response status code and the response text in the xhr object to understand what is going wrong. If you're seeing a 200 OK response status, the data returned from the server is probably not being interpreted correctly as JSON data, so you should try setting the response header server side to application/json.
An error might occur also if something else is appended or prepended to your response. This happens especially when warnings occur in the code before returning and you have error reporting set to ON.

Related

Using ajax long polling to update a response on my page from an external API

I have the following ajax long polling script
(function poll(){
$.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn'); ?>", success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
}, dataType: "json", complete: poll, timeout: 1000 });
})();
The backend PHP code is as follows
if(isset($_POST['status']) && $_POST['status']){
$data = ['status'=>$_POST['status']];
$json = json_encode( $data );
echo $json;
}
Flow
When I render the page, the ajax script runs and waits for response. When I checked the network tab, ajax was endlessly making requests to the URL specified.
I get a form post from an external website to the backend PHP which I need to push to the jquery.
But when a post is happening, nothing is being logged in the console. But if I hard code some values in the $json and echo it, its coming up in the console.
I am facing two issues
When a post happens on the PHP script, its not coming up in the ajax code.
When I hard code (simulated the response posted by the external form post) the $json and echo it, its coming up in the console, but the condition for data.status== 'success' is not getting checked.
What is wrong in this. Am I missing something?
UPDATE
I could fix the "condition not being checked" as there was something wrong the json being echoed.
Now to avoid confusion, the flow for this
User open the page,
> The ajax starts the long polling process to my PHP code, waiting for a
> response.User enters payment details in a form which is my html,clicks on pay, a pop up appears
> which renders the banks login page (Payment gateway).After user entering all
> details in the pop up (banks page), bank sents a server to server call about the status of
> transaction to my notificationURL
> ('mydomain.com/internal.v1/checkTxn'). As soon as I get a POST on this
> URL(I will close the pop up), my ajax polling should get the data posted to my PHP and there by
> I will show the status of TXN to the user on the same card form he entered his details earlier and
> the pop window closes. The response here is returned by my PHP code to the ajax.
The
> post coming to my PHP code is a server to server post which is posted
> by a Payment Gateway.
1. let's debug this:
set your ajax error call back,
$(function(){
(function poll(){
$.ajax({ url: "http://tinyissue.localhost.com/test.php", success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
},error:function(err){
console.info('error fired...');
console.info(err);
}, dataType: "json", complete: poll, timeout: 1000 });
})();
});
run this, you will get console
error fired...
Object {readyState: 4, responseText: "", status: 200, statusText: "OK"}
2. Why went to error callback:
Why ajax response status is 200 and statusText is "OK" , error callback still fired instead of success?
Your AJAX request contains the following setting:
dataType: "json"
The documentation states that jQuery:
Evaluates the response as JSON and returns a JavaScript object. (...)
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Solution: make sure that the server returns valid JSON. It is worth noting that an empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
3. Why ajax return invalid JSON:
In your mind, at server side, you checked the $_POST['status'] to make sure last call success in the loop poll, only $_POST['status'] is set, you will echo json, or it echo nothing.
But, unfortunately, at the beginning of the call loop, the first time the ajax called, you didn't set status to post. Then it echo nothing, then it went error callback, also went complete callback, then call again without status to post. See, it went a bad cycle.
4. Solution:
Set a status value to post at the first ajax call.
$(function(){
(function poll(){
var status = 'success';
$.ajax({ url: "http://tinyissue.localhost.com/test.php", success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
status = data.status;
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
},error:function(err){
console.info('error fired...');
console.info(err);
status = 'error';
}, type:'post',dataType: "json", data:{status:status}, complete: poll, timeout: 1000 });
})();
});
If you are using long polling, you could have a cache issue.
First, when your post comes to your system, check that checkTxn changes.
Last, you can add a random parameter (by adding date in millis, for example) in url query, you will not use it, but your server will think your requests are different.
Please, check it and let us know.
#Edit: Sure #Ajeesh, I'll explain it:
(function poll(){
$.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn'); ?>?_ts=" + new Date().getTime(), success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
}, dataType: "json", complete: poll, timeout: 1000 });
})();
By doing this, cache will not be used, because all queries are different for your server/browser.
On the other hand, I ask you for any changes in your page when you receive the POST, so, if not, your ajax will never receive the notification, do you know what I mean?

Better way to response to AJAX from php

I have one javascript file which sends AJAX request to php file, which fetch some data from database. If php finds any data it return it as json object in response, but when it does not find any recrod in database based on query, it return a message something like "not match found".
It means javascript either get string message in "not match found" or json object.
I am trying to check if xmlhttp.responseText is json object or a string, but have not been succedeed. Any idea about how to solve this problem?
Should I convert "not match found" string into a json and send back to javascript and then parse it or there is any better way to solve this?
Thank you
BR
I don't think you need to parse your error message "No match found". There's two options: either create an if/else statement in the PHP file that the ajax calls, or you can attempt to encode the JSON in the php file and if it's unsuccessful, you can just write out a "No match found" message in the error part. I highly recommend using the $.ajax call because it can handle the responses better.
JS
$.ajax({
url: "myFile.php",
dataType: "json",
success: function(data) {
var myNewJsonData = data;
alert(myNewJsonData);
},
error: function() {
alert("No match found.");
}
});
PHP (myFile.php)
<?php
//Do your query business and stuff here
//Now let's say you get back or store some array that looks like this for example
$myArray = array('name' => 'Mike', 'age' => 20);
/* Now attempt to create a JSON representation of the array using json_encode() */
echo json_encode($myArray);
?>
When you echo it out, it gets sent back through either the $.ajax's call success or error function as a parameter (which I named data), depending on whether or not there was an error reported back. If there was not, then success is called, and if there is an error, well then you can guess which one gets called. json_encode will create a JSON representation of the array of data that you get back from your query.
Maybe I'm not understanding your question, can't you just print out an error using something like this:
$.ajax({
url: "myphpfile.php",
dataType: "json",
success: function(data){
alert(data.info);
},
error: function(xhr, status, error) {
alert(status);
alert(xhr.responseText);
alert(xhr);
}
});
Then do something inside of the error block?
Even though I totally agree with Patrick Q's comment, there is another option that has not been mentioned. You could also set the Content-Type of the response to indicate if it's json or text:
#header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
and
#header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) );
or even,
#header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
Then you could check the response's content type to make a decision:
$.ajax({
type: "POST",
url: "xxx",
data: "xxx",
success: function(response, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//do something
} else
if (ct.indexOf('json') > -1) {
// handle json here
}
}
});
A.

Get json ajax php form to work remotely

So, essentially I have this Javascript which interprets the JSON from my php code. It works great on the local server, however, when I try to move the script to a different server it will not work. I have added the
<?php header("Access-Control-Allow-Origin: *"); ?>
also i've declared my database connection as global within my PHP function.
I'm confused as to why these solutions aren't working.. Also, I understand some of the script is iffy, but I'm only interested in figuring out why its not working from different servers.
<script type="text/javascript">
$("document").ready(function(){
$(".sendText").submit(function(){
$("#sendButton").prop("disabled",true);
$(".errors").html("");
$(".success").html("");
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "jsonp", //new edit
url: "http://myurl.com/testing/jsonpost.php?callback=test", //new edit
data: data,
success: function(data) {
if(data["success"]=="yes") {
$(".success").html("Message Sent!");
$(".formContainer").html("" + data["json"] + "");
}
else {
if(document.getElementById("sendButton").disabled = true){ document.getElementById("sendButton").disabled = false; }
$(".errors").html("" + data["errors"] + "");
}
}
});
return false;
});
});
</script>
Some Info when I look at the web console from firebug:
Access-Control-Allow-Orig... *
Connection Keep-Alive
Content-Length 0
Content-Type application/json
Date Wed, 24 Sep 2014 04:22:57 GMT
Keep-Alive timeout=5, max=100
Server Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips DAV/2 mod_bwlimited/1.4
X-Powered-By PHP/5.4.29
Looks like it is communicating with server but not able to interpret data? thoughts?
Also, this error comes up in the console from the remote server but not when I run on local server:
SyntaxError {stack: (...), message: "Unexpected end of input"}message: "Unexpected end of input"stack: (...)
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…
parsererror
The PHP code is pretty long (and I prefer not to release all of it) - however here is the shortened version:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
require "../database/db.php";
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$c="1";
global $con;
$return = $_POST; //to reference post
$content=$return["content"];
//see if content is 140 characters or less
if(strlen($content)>140){ $c="0"; $lerror="<li>Your message must be 140 characters or less in length!</li>"; }
if($c=="0"){ //doesnt pass validation
$return["success"]="no";
$return["errors"]="$lerror";
}
if($c!="0"){ //passes validation
$return["success"]="yes";
}
if(isset($_GET['callback'])){ //jsonp edit
$return["json"] = json_encode($return);
echo $_GET['callback']."(".json_encode($return).")"; //jsonp edit
}
}
Also after converting to JSONP on remote server - get error -
"jQuery111006159528985153884_1411663761720 was not called"
When dealing with jQuery AJAX using a data type of JSON, any notice, warning or error produced by the server side script will cause issues. The reason being is the outputted PHP errors break the JSON encoding that jQuery is expecting.
I suspect the two environments are not identical, perhaps a different PHP version, missing PHP extension or different settings in the php.ini file.
The best thing to do is to use the provided jQuery AJAX error callback to console log any errors allowing you to essentially troubleshoot any issues being thrown by the server side script.
!!! EDIT 3 !!!
Client Code
$.ajax({
type: "POST",
dataType: "json",
url: "http://myurl.com/jsonpost.php",
data: data,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
Server Side Code
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
echo json_encode(array('success' => 'yes'));
Using this bare bones version of your code I can successfully make a cross domain request and console log the response. If you implement this code and it still does not work there is something else at play at the server and/or network level.
You can make AJAX calls to a backend API, it needs to return JSONP format and not just JSON, otherwise you can get error. This is due to same origin policy:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy.
This discussion may be helpful to understand JSONP:
Can anyone explain what JSONP is, in layman terms?
However, one alternative is disable the security of Google Chrome browser, then it will work. But this is not a solution. It is better to use JSonP format.

Ajax fails 5% of time, response is "error"

I'm using jQuery to handle Ajax-calls.
I've noticed that, about 5% off the time, the ajax call fails. To make sure I get a good understanding of what's going wrong, I use this code:
$.ajax({
type:'POST',
url:'somepage.php',
data:{somedata:somedata},
success:function (data) {
var IS_JSON = true;
try
{
var newdata = jQuery.parseJSON(data);
}
catch(err)
{
IS_JSON = false;
}
if(IS_JSON)
{
//this is the part where a correct response is handled
}
else
{
//In case somepage.php gives a php-error, I put the exact error (=data) in the error-table at error.php.
window.location = "error.php?errorstring="+data;
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
//In case the ajax errors, I store the response (timeout, error, ...) in the database at error.php
window.location = "error.php?errorstring="+textStatus;
}
});
"Good" responses contain JSON, which I parse. If it's not JSON (for example just raw text from an php error) I don't try to parse it, but store the error in my database.
I would understand errors containing php errors that occured on somepage.php (since it's quiet a large page), but I'm supprised that the main errors I get, are errors of the ajax failing. The response data is just "error".
Anyone knows what the cause could be? What causes ajax-calls to fail? It's not a timeout, and it's also nothing like that somepage.php wasn't found or something. It's also not an error on somepage.php, since in that case, the Ajax-call would be successful, and the php-error would be logged in my database.
Edit: I used this obfuscator to make the script a little harder to read... Don't know if this could be causing the errors...
You should set dataType: 'json' in your ajax call. Coz if your not setting this up and your expecting a json result, the result will be treated as 'string' by default.

JQuery gives JSON syntax error when using PHP's json_encode

I have an application that uses JQuery $.ajax to send JSON encoded data to server where I process it and then send back the results also JSON encoded. The problem is that JQuery gives a parse error when I want to process the response. (As if PHP's json_encode function outputs an invalid JSON format).
Here comes the code:
The Javascript code:
$.ajax({
type: 'POST',
url: URL+'pages/processListUIAjaxRequest',
data:{filters: filters, rebuild_params: $('#rebuild_params\\['+unique+'\\]').val()},
dataType: 'json',
success: function(response){
alert(response);
},
error: function(request, status, error){
alert('Unable to update table contents');
console.log(request);
console.log(status);
console.log(error);
}
});
This is a piece of the PHP code which outputs the response:
$response->addResult($uFilters);
header('Content-Type: application/json');
$response->toJSON(true);
The $uFilters is a simple array, and the toJSON method of the $response object is here:
public function toJSON($output = false){
$out = array();
if($this->hasErrors()){
$out['has_error'] = true;
$out['errors'] = $this->getErrors();
} else $out['has_error'] = false;
$out['result'] = $this->_result;
if($output){
echo json_encode($out);
}else{
return json_encode($out);
}
}// toJSON
Every time I run the code i get the 'Unable to update table contents', and on JavaScript console I have:
'SyntaxError: JSON.parse: unexpected character'
despite I defined dataType: as 'json' and the output is json_encode'd by PHP. On the JavaScript console I can see that the response text is:
"{"has_error":false,"result":{"page_id":"xxx"}}"
Tried copy this and validate with online JSON validator tools, the interesting thing is it was valid a few times and it was invalid a few times (without any consistency) Im a bit confused.
Tried to use other headers like:
header('Content-Type: text/json');
header('Content-Type:javascript/json');
header('Content-Type: application/json');
or with no header, but nothing.
If I edit the JQuery ajax request's dataType to 'text' (despite the output is JSON formatted and and even the header says it is a JSON content), then the success handler runs and I got the response correctly. In this case the same problem comes when I try to $.parseJSON(response).
What went wrong? Is my JSON string really invalid?
Debug your response to see what characters are there that is making it not valid. Set the dataType to text and escape the text that is returned.
dataType: 'text',
success: function(response){
console.log(escape(response));
},
You will see the characters that are returned, there is probably some weird return character that is cauing the problem.

Categories

Resources