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.
Related
I have a PHP script on my server that needs to be run from my clients websites using Javascript in a plain HTML page. After the script is run the HTML page will redirect. The problem is that sometimes the script doesn't run before the redirect happens.
This is the code I am using...
$.ajax({
async: false,
type: 'GET',
url: 'the_URL_of_the_PHP_on_my_server.php',
success: function(data) {
}
});
window.location="the_URL_for_the_redirect";
The PHP script on my server is to track hits/sales etc. Is there are way I can force the page to wait for the script to complete before the page redirect.
The HTML page and the PHP page are on different servers. Also, the HTML page is being used on lots of different websites, so I can't give them all permission to access my server. I'm not sure if that's causing a problem or not.
I don't need any information back from the PHP script I just need it to run.
Thank you.
The success function runs when you get a response (unless it was an error, in which case the error function you haven't defined would run).
If you want some code to run after you get a response, put it inside those functions instead immediately after the code which sends the request.
That said: The point of Ajax is to talk to the server without leaving the page. If you are going to go to a different page as soon as you have a response, then don't use Ajax. Use a regular link or form submission and then having an HTTP redirect as the response.
This is normal, that this situation happens.
because $.ajax is async and won't wait till success method
change your code to
$.ajax({
async: false,
type: 'GET',
url: 'the_URL_of_the_PHP_on_my_server.php',
complete: function(data) {
window.location="the_URL_for_the_redirect";
}
});
UPDATED
changed function success to complete
difference is =>
complete will be called not matters what happened with request
UPDATE 2
think about #Quentin variant by html redirects.
I have done this hundreds of times and it seemed to work like a charm.But I just can't figure what is wrong with this code.
$.ajax({
url:"<?php echo base_url() ?>admin/sold_item",
data:{qty:sold,tprice:sold_price,id:id,uprice:uprice},
type:"post",
async:true,
success:function(msg){
if(msg=="info_saved"){
$('#sold_data').html('Your Sold Details Have Been Saved');
setTimeout("$.colorbox.close()",1500);
// setTimeout("window.location.reload()",1800);
}
else if(msg=="wrong"){
$('#sold_data').html('Your Information is Incorrect!!Enter Data Again!!');
setTimeout("$.colorbox.close()",1500);
// setTimeout("window.location.reload()",1800);
}
}
})
I am using condition for the response.The php code called by ajax is working perfectly
this is the exact code that I am using for ajax.I have alerted the msg variable and firebug console shows the same but the if condition is just not working.What can be the reason.I have tried switch ..case but to no avail.Please somebody see what I am not seeing.
Use the developer tools in chrome and go to the network tab and then select the XHR button at the bottom left of the screen. This will show you exactly what is happening and you can read the response or see an error if there is one.
Your URL seems wrong. admin/sold_item there is no file extension.
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.
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
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)