PHP interaction with AJAX - php

So I have this function in my javascript file:
function UpdateThisCourseHistory(){
var ajax= new Ajax.Request("runNeededQueries.php",
{
method: "POST",
parameters: {database: "history", action:"update"},
onSuccess: function(){alert("This Course History Entry Has Been Updated");},
onFailure: function(){alert("Could Not Find The Entry With The Specified Primary Key");}
}
);
}
Suppose this is my php file
<?php
header('HTTP/1.0 400 Bad Request');
?>
Would this make the onFailure method execute?

The onSuccess callback will fire when the PHP script responds with an HTTP 2xx response code and the onFailure callback will fire if an HTTP error code is returned. If you want to take action based on the response value, you have to options:
Modify your PHP script to return an HTTP error response (perhaps 400) on failure and take action based on the specific value returned.
header('HTTP/1.0 400 Bad Request');
Update your AJAX handler to inspect the data that is returned and take action based on its content.
onSuccess: function(transport){ if transport.responseText == 'expected value' ...}

Make your PHP script output something, preferably in JSON.
Like:
{ action: 'find_id', status: true }
Get the data from response, so you can see if an action was successful or not.
function(data){
if (data.status){
alert("Everything is OK") ;
} else {
alert("Failed") ;
}
}

Related

how to manage errors server side (php) when Ajax is involved?

So, I have an ajax call that prevents default post submission, server side I do some validation and checking, if the data is correct I do some database operations (inserting item for user etc) but if the data is not correct I don't have to make anything but throw out an error (i.e. item already present). My case in the controller was something like this:
} else {
print('Item already present');
}
but now I have the ajax call that manages the error like this:
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
So obviously the php doesn't print anything.
How should I modify my php to act well with the ajax call?
When you make an ajax call, you should be expecting a particular type of data back. A typical (example) scenario is to get back data in JSON. If you are using jQuery, then I typically to look for errors in a two places because I think of ajax errors coming in two types:
network error or anything that results in a website error (404 - page not found, 500 - potential coding error, etc). This is caught in the ajax 'error' handler function as you have it above. I believe you could intentionally trigger an error in your PHP code to get this case.
logical error. This is an error that you might be expecting to handle - such as a bad username/password during a login call via ajax. In this case, you don't really want to throw a PHP error. Instead you want to return an error, but perhaps also include some meta data bout the error such as 'username does not exist' or whatever.
So, on your php server, you would have a view that needs to set the header to be a JSON response, and then output the JSON error, e.g.:
<?php
// output a json version of any list of objects that has the
// "toArray()" method defined.
// ...for ajax calls.
header( 'Content-type: application/json' );
$isError = 'false';
if (checkToSeeIfErrorOccurred())
{
$isError = 'true',
$errorMessage = getErrorMessages();
}
?>
<!-- define json result -->
{
error: "<?php echo $isError; ?>",
errorMessage: "<?php echo $errorMessage; ?>"
}
So, on your client side, in (for instance) your jquery ajax call, you would define a successHandler that needs to check for this error, and specify the dataType of the return value. Note that even though it is a successHandler, the 'success' part just means you had no network or programmatic/PHP error thrown. So, you still need to check for the logical error you might return in your JSON:
// your error handler
function myErrorHandler( xhr, status, errorThrown )
{
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
};
function mySuccessHandler( response )
{
// response is returned as an object
if (response.error === 'true')
{
// maybe call same error handler?
myErrorHandler( 'whoCares', 'logicalFailure', response.errorMessage );
}
else
{
// handle success
}
};
$.ajax(
url,
dataType: 'json',
error: myErrorHandler,
success: mySuccessHandler,
...
);
I don't know if this is typical for other folks and it is only an example but it has worked well for me...
One way you could think about this is use ajax to do your request and then return xml with a result from php echo statement. If the result is successful then your code does what it needs to do else as part of the php server return you have an xml error tag with why it went wrong and then process this in your ajax.
Another way you could return a result is with json.

After a JQuery Ajax call, unable to remove "X-Requested-With" from subsequent Slim URL redirect request headers

After a JQuery AJAX call, all subsequent Slim redirects includes "X-Requested-With:XMLHttpRequest" in the request header. As a result, content of the redirected page is being returned in the background in the response, but browser is not redirecting to the intended URL. Not sure what I am doing wrong here.
My Ajax call is given below (this is an implementation of: https://developers.google.com/+/web/signin/server-side-flow):
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'GET',
url: '../google/',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
console.log(authResult['code']);
},
data: "gplustoken="+authResult['access_token'],
error: function (request, status, error) {
console.log("Error");
}
});
} else if (authResult['error']) {
// There was an error.
}
}
}
PHP Slim URL redirect code is given below:
$app->redirect($app->urlFor("home"));
For the context of above line, kindly see:
https://github.com/TheRosettaFoundation/SOLAS-Match/blob/master/ui/RouteHandlers/UserRouteHandler.class.php#L413
I tried to remove the 'X-Requested-With' from the request header in the PHP/Slim Code as below, but it did not work either.
$isAjaxRequest = $app->request->headers->get('X-Requested-With') == 'XMLHttpRequest';
if ($isAjaxRequest) {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']))
{
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
//$app->request->headers->set('X-Requested-With','');
$app->redirect($app->urlFor("home"));
}
} else
$app->redirect($app->urlFor("home"));
Any help to resolve this issue is much appreciated.
Looking at the Slim docs for the Http Headers object, you should be able to achieve this by calling the remove method:
$app->request->headers->remove('X-Requested-With');

can't make cross browser AJAX request to work

I am doing a simple ajax request to another domain like this:
<script type="text/javascript">
$(function() {
$('.clik').click(function() {
$.ajax({
type: "POST",
url: "http://sub.mydomain.com/test.php",
crossDomain: true,
dataType:"jsonp",
success: function(data) {
$('p.txt').html(data['no']);
}
});
});
});
</script>
</head>
<body>
<p class="clik">Halleluja</p>
<p class="txt"></p>
this is the test.php page on sub.mydomain.com
<?
header('Access-Control-Allow-Origin: http://mydomain.com');
// Begin Session
require_once('cl.session.php');
$session = new Session();
$session->start_session('test', false);
// Access Database
require_once('cl.database.php');
$login_db = new Database('user', 'pass', 'accounts', 'test');
$login_pdo = $login_db->PDO;
include "fn.check_login.php";
if(checkLogin($login_pdo) == true) {
// We start out by checking if the request has been made using AJAX
if (is_ajax()) {
echo "this is working";
} else {
echo "this is not working!";
}
} else {
echo 'You are not authorized to access this page, please login. <br/>';
}
// Function to check if the request is an AJAX request
function is_ajax() {
// BOOLEAN return if AJAX
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
It returns a semantic issue.
Also if I simply echo some basic text:
<?
echo "Hello World!";
?>
it still returns a semantic issue.
could somebody tell me what went wrong?
Well, for a start, JSONP requests can't be POST (only GET). But I tend to assume jQuery is ignoring the invalid type. JSONP is intrinsically a GET.
Your response to it is invalid. You've told jQuery you're expecting the server to provide a JSONP response. but your responses aren't JSONP.
A JSONP response would look something like this:
callback({
"property": "value",
"anotherProperty": 42
})
...where the name of the callback (callback in the above) is taken from the query string of the request. So for instance, if the request were http://sub.mydomain.com/test.php?callback=foo, the response would use foo for the name of the callback:
foo({
"property": "value",
"anotherProperty": 42
})
jQuery will add the callback= query string parameter to the request for you automatically, and generate the corresponding function for you, which in turn calls the ajax success handler with the data passed into it.
I think you may need to use the jquery postMessage plugin (or similar if there is one). Long time since I tried it but check if you load the script from the server you wish to call (think I tried that and failed in the past but hey - its worth a bash - report back if it does).

jQuery ajax success conditional..?

I'm running the following php script through AJAX and need to integrate some error management into it:
$exists = file_exists('../temp/' . $email . '/index.html');
if($exists) {
echo "ERROR!!!";
} else {
createUserDirectory($email);
}
In the AJAX success function, how can I determine whether the script ran successfully or produced an error?
If it returns OK, I want to perform the redirect as it is at the moment, but if there's an error, I want to instead add the error to a DIV within the document (and not redirect of course...).
$.ajax({
type: "POST",
url: 'generate/build.php',
data: $("#generateStart").serialize(), // serializes the form's elements.
success: function(data)
{
window.location.href="generate-site.php?user=" + data.replace(/^ +/,"") + ""; // Redirect to publish.php and remove any spaces from the URL (bug fix).
}
});
Thanks.
Your PHP script should return a 4xx or 5xx HTTP status code to indicate failure. Then, the error method of jQuery's ajax object will be called.
Inside your success handler, check if(data == 'ERROR!!!').
You probably want to add two parts to this: an error callback on the $.ajax function to see if the request failed on the net and then a check on the return value to see if it failed server validation (if a file exists in this case).
Example:
$.ajax({
...
success : function(data) {
if(data && data != "ERROR!!!") {
//redirect
}
},
error: function(jqXHR, textStatus, errorThrown) {
//Log error, display feedback to user, etc...
}
);

How can I "read" a response from the php file I call here using ajax?

I am very new to ajax and jquery, but I came across a code on the web which I am manipulating to suit my needs.
The only problem is that I want to be able to respond to the ajax from PHP.
This ajax POSTS to a php page (email.php).
How can I make the email.php reply back if the message is sent or if message-limit is exceeded (I limit the nr of messages sent per each user)?
In other words, I want ajax to take a 1 or 0 from the php code, and for example:
if(response==1){ alert("message sent"); } else { alert("Limit exceeded"); }
Here is the last part of the code: (If you need the full code just let me know)
var data_string = $('form#ajax_form').serialize();
$.ajax({
type: "POST",
url: "email.php",
data: data_string,
success: function() {
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}//end success function
}) //end ajax call
return false;
})
Thanks
The success function of an $.ajax call receives a parameter, usually called data though that's up to you, containing the response, so:
success: function(data) {
// Use the data
}
(It also receives a couple of other parameters if you want them; more in the docs.)
The data parameter's type will vary depending on the content type of the response your PHP page sends. If it sends HTML, data will be a string containing the HTML markup; if your page sends JSON, the data parameter will be the decoded JSON object; if it's XML, data will be an XML document instance.
You can use 1 or 0 if you like (if you do, I'd probably set the content type to "text/plain"), so:
success: function(data) {
if (data === "1") {
// success
}
else if (data === "0") {
// failure
}
else {
// App error, expected "0" or "1"
}
}
...but when I'm responding to Ajax requests, nine times out of ten I send JSON back (so I set the Content-Type header to application/json), because then if I'm using a library like jQuery that understands JSON, I'll get back a nice orderly object that's easy to work with. I'm not a PHP guy, but I believe you'd set the content type via setContentType and use json_encode to encode the data to send back.
In your case, I'd probably reply with:
{"success": "true"}
or
{"success": "false", "errMessage": "You reached the limit."}
so that the server-side code can dictate what error message I show the user. Then your success function would look like this:
success: function(data) {
var msg;
if (typeof data !== "object") {
// Strange, we should have gotten back an object
msg = "Application error";
}
else if (!data.success) {
// `success` is false or missing, grab the error message
// or a fallback if it's missing
msg = data.errMessage || "Request failed, no error given";
}
if (msg) {
// Show the message -- you can use `alert` or whatever
}
}
You must pass an argument to your "success" function.
success: function(data)
{
if(data == '1')
{
$('form#ajax_form').slideUp('slow').before('');
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
}
And in your php file, you should just echo the response you need
if(mail())
{
echo '1';
}
else
{
echo '0';
}
Anything you echo or return in the php file will be sent back to you jquery post. You should check out this page http://api.jquery.com/jQuery.post/ and think about using JSON formatted variables to return so like if you had this in your email script:
echo '{ "reposonse": "1" }';
This pass a variable called response with a value of 1 back to you jquery script. You could then use an if statement how you described.
just have email.php echo a 0 or 1, and then grab the data in the success event of the ajax object as follows...
$.ajax({
url: 'email.php',
success: function(data) {
if (data=="1"){
...
}else{
...
}
}
});
what you do is, you let your ajax file (email.php) print a 1 if successful and a 0 if not (or whatever else you want)
Then, in your success function, you do something like this:
function(data) {
$('form#ajax_form').slideUp('slow').before('');
if(data==1){ alert("message sent"); } else { alert("Limit exceeded"); }
$('#success').html('<h3>Success</h3>Your email is has been sent.');
}
So you capture the response in the data var of the function. If you a bigger variety in your output, you can set you dataType to "json" and have your php file print a json_encoded string so that you can access your different variables in your response via for example data.success etc.
PHP can only return to AJAX calls, by its output. An AJAX call to a PHP page is essentially the same as a browser requesting for the page.
If your PHP file was something like,
<?php
echo "1";
?>
You would receive the "1" in your JavaScript success callback,
that is,
success: function(data) {
// here data is "1"
}
As an added note, usually AJAX responses are usually done in JSON format. Therefore, you should format your PHP replies in JSON notation.

Categories