.ajax() sometimes returning errors, sometimes not - php

I have the following jQuery code which, when running to the server, will sometimes return success and sometimes return error (running the alert box), depending on the user running it. It's not 100% consistent. What could be wrong? The page is loaded via an iFrame in a Facebook Tab.
The entryform.php sometimes echos and returns a message, and othertimes it returns a failure, which causes the .ajax() to trigger the error. Nothing in the server side script looks fishy though - it's set up to always return a successful message. Anything sticking out from the jQuery code?
The page returns a 200 OK status, but appears red in Firebug. What error am I missing?
jQuery:
$(document).ready(function() {
$('#entryform_submit').click(function(e) {
e.stopImmediatePropagation();
e.preventDefault();
$('#entryform_submit_loader').show();
var form_data = $('#entryform_form').serialize();
$.ajax({
url:'http://www.myurl.com/entryform.php',
type:'POST',
data:form_data,
success:function(return_data){
//do stuff
},
error:function(w,t,f){
alert('Error submitting entry. Please try again later.');
}
});
});
});

Got it! The key was Facebook - if a user is browsing in HTTPS, the page gets called in HTTPS - but, the .ajax() call was calling a HTTP page, which gets set as cross-domain, which is not allowed.
The key was to determine if the page is being viewed in HTTP or in HTTPS using this:
if (!empty($_SERVER['HTTPS'])) {
// https is enabled
}
And then making the appropriate AJAX call, either to the HTTP or HTTPS version.

Related

Unable to make a ajax async post request to the same page

I'm trying to make an async call to the same page but for some reason, the async call is not being made and hence getting "userinfo" undefined error! could someone please tell me what I'm doing wrong in this thank you!
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready(function() {
//getting location of the user and assigning it to the variable
$.get("http://ipinfo.io", function (response) {
var usercity=response.city;
console.log(usercity);
$.ajax({
//no need to provide url since we are making async call on the same page
type: "post",
data: {cityinfo:usercity},
});
}, "jsonp");
});
</script>
<?php
session_start();
$usercity=$_POST['cityinfo'];
echo $usercity;
?>
First, you make a regular request to the PHP page. $_POST['cityinfo'] is undefined at this stage because you don't set it. The page includes an error message telling you that.
Second, you make a JSONP request to ipinfo.io, and call a callback function when you get a response.
Third, you make a second HTTP request to the PHP page. This time you do define $_POST['cityinfo']. You have no success handler to do anything at all with the response so, although $_POST['cityinfo']; is set, you don't see any effect of that (unless you were to use the developer tools Network tab to examine the response itself).
It is important to note that this is a second, distinct request to the same URL. The JavaScript does not travel back through time and set the $_POST['cityinfo']; variable in the previous request (and it is the response to the previous request that is still displayed in the browser window).

jQuery Ajax only executing once, but appears to call every time it should

Currently, I have set up an ajax call, that on change of a particular field it should execute a php script. The script first executes on page load.
AJAX Call
$j.ajax({url: prod_json_url, dataType: 'json', cache: true,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=x-user-defined' );
},
success: function(data) {
//things to do on success with JSON
}
});
Everything works great in my virtual environment for testing, but when I deploy this to a different server the following happens.
1) On page load, I can view the URL in FireBug being executed and returning the correct JSON Response. Logging shows that it did go to the script to be executed and returns the correct data. Everything acts as it should.
2) I then click to update the field. By viewing Firebug in the Console again, the correct URL is being executed, however, the JSON response is incorrect. It keeps the same one that occurred on page load. When I added logging, it appears that it never actually reaches the updated URL. (Which is the same URL as page load with updated arguments).
3) If I wait some time, and try again, it sometimes behaves as it should again, but only for the one execution.
This behavior makes me believe it is a cacheing issue. Does anyone have an idea of how I can resolve this or what variable I should be looking for or checking? The database is exactly the same and I'm not sure what else might be causing this. Any help is greatly appreciated! Please let me know if more information would be helpful as well.
Try adding the current time to the url you're loading data :
prod_json_url + '?ts=' + $.now()'
Cache control HTML headers apparently are ignore on Ajax requests in IE, therefore cache:false isn't enought. This should work though.
$.now() is a shortcut to new Date().getTime();
Set cache to false. Seems like theres client caching
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
try this copied from limk

How can I detect an error in AJAX?

I have a jQuery function, which is using AJAX to send the necessary information to run the respective script properly:
$("#changeUseridForm").submit(function(){
$.ajax({
type: "GET",
url: "API/root/users/changeUsername.php",
data: {
newUsername: ("#newUserid", this).val(),
password: ("#retypePass", this).val(),
xml: 1,
},
dataType: 'xml',
success: function(xml){
if($(xml).find("success").length > 0){
alert("Username changed successfully!");
$("#changeUserid").hide();
$("#BackToMainMenu").hide();
$("#MainPage").show();
$("#AddLinkButton").show();
$("#ChangeUserOptions").show();
$("#ChangeUserDataButton").show();
$("#ShowPosts").show();
}
else if($(xml).find("error").length > 0){
alert("You have to fill all the fields!");
}
}
});
return false;
});
I have several functions like this one, running perfectly; this one isn't. I verified all my variables and scripts. They're spelled correctly. It doesn't reach to the script referenced. I think the AJAX code might have a problem, but I can't detect which error is. I tried to search it on my browser's web inspector, but I can't figure it out since the page is reloading for some reason that I don't know why. (Because this function doesn't have window.location.reload() in it anywhere.)
try to set up a proxy or use firefox plugin to catch the get request(you can also use wireshark)
then you can see if there's a request to this page API/root/users/changeUsername.php
it is possible that this page API/root/users/changeUsername.php returns 302 redirect,
Check the http response of the GET Request and post it please
Look in the docs on .ajax(), you can specify an error handler function that gets details about what went wrong. That would be the first step.
You can also use Firebug's or Chrome's "Net" tab to monitor the request, and see what was returned.
You can detect (debug) a lot of errors using firebug. In this case you can use the net tab and check persists to see what request is causing reloaded page.

Jquery post to php file works but can't return the data echoed in php

I can post the data using jquery (Checked with the mysql insert from that php file, it does insert, so i'm 100% sure that posting works), even though something is echoed in the php file, i can't seem to return that to the page with my data function (also checked if it echoes normally)... I know it should work, any ideas why it wouldn't?
$('#formbutton').click(function() {
var user = $('#nameinput').val();
$.post("usercount.php", {
username: user
}, function(data) {
alert("Data Loaded: " + data);
});
});
If the data is inserted, there should't be anything wrong with the request. My guess is that a fatal error occurs after the data is inserted, thus preventing the output. You should check your PHP logs for a clue.
You should also check the response code of the request in the Net panel in Firebug or similar tools. If the response fails, the callback function in $.post won't execute. Try using the $.ajax function instead, and provide both a success and an error callback.
Everything seems correct (or at least I can't see anything wrong now).
Use the network panel in firebug or chrome developer tools to inspect the request and the response of the ajax calls and see if they are correct (and also if the response comes with http status code 200). Also check the javascript console, put a breakpoint here or there and play with it (it's fun :D)

how to redirect the browser during an ajax call (made using jQuery) in php

i am facing a problem of redirecting the site while in an ajax call..
here is what i wanna do :
make an ajax call to the server.
it goes to a certain process, if an error occurs, i should send to the error page, else resume.
now the problem is when in the server side, if i use :
header('Location: error.php');
It doesnt redirect the page, infact it just brings the data of that page (the whole html) to the javascript success function.
The problem is that i have made a generic library both on the javascript side (to call the ajax) and on the server side.
i need to redirect the page through the server side. i tried adding a js code for
window.location='error.php';
but didnt get any success
Why not return an error that the Ajax query can understand instead?
if ($error)
{ header("HTTP/1.1 500 Internal Server Error");
echo "A database error has occurred. etc.etc.";
die();
}
this will trigger the Ajax request's error callback (if in jQuery). The echoed text will be in the response body.
You can also look for a more fitting status code depending on the situation.
I think you should have an error handler in your ajax lib. In the server you send back either the correct html or an error code in the header plus the URL to redirect to in the body. In the ajax lib the error code in the header will trigger the error handler. In the error handler you can redirect using window.location = 'page_returned_by_server'
If an error occurs, simply echo the url of the errorpage. For example, using JSON:
Server-side:
echo '{error: "error.php"}';
Client-side:
var xhr = $.ajax({ url: "example.php" })
.success(function() {
var obj = JSON.parse(xhr.responseText)
if obj.error {
window.location = obj.error;
}
})
Have you considered using the $.ajaxError() global AJAX event?
$(document).ajaxError(function(event, jqxhr, settings, exception) {
alert('An AJAX error occurred in script: ' + settings.url);
console.log(event, jqxhr, settings, exception);
});
In your main JS lib could do the trick and you can add any type of redirect you like.
Here's the official jQuery documentation..

Categories