JQuery If Else statement never executed - javascript

I'm using a simple if else statement to check for response from a POST form.
This is weird: I can check for response in form of error. Using elseif: or else: just does absolut nothing. Even though the response is valid.
Current code:
post_data = {
'someData': someData
}
// Ajax post data to server
$.post('register.php', post_data, function(response) {
if (response.type == 'error') {
if (response.errorType == 'something') {
$("#someThing").addClass('has-error');
}
} else {
window.location.reload(true);
}
}, 'json');
This is so weird. I've tried to insert alerts to really check if the else statement ran in background or something.
When the response is: "error" the error statement is executed.
However when the response is: success/done/cleared/failed etc. (whatever i try) nothing happens.
I receive the respond in console - but JQuery doesnt run the } else { ... statement.

Actually its not what you think.
The function is only called on Success. For error handling you have to chain another function
For example try this:
post_data = {
'someData':someData
}
// Ajax post data to server
$.post('register.php', post_data).done(function (response) {
// This is your success function
window.location.reload(true);
})
.fail(function (xhr, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
$("#someThing").addClass('has-error');
});
I hope this help you to understand that weird behavior :P
jQuery documentation have different handling functions for different jQuery version. so better to use $.ajax

Related

jQuery Synchrnus issue with alertifyjs success method

I m facing a strange issue. i have used alertify library to show messages to user, but in this case alertify is not working. Here is the success portion of my ajax call.
success: function(data) {
if (data.status == 'success') {
alertify.success(data.msg);**// this line should dislay a message but instead of calling this , it directly calls employee_details(), data.msg is "Data saved Successfully"**;
data.user_type =3;
if(data.hasOwnProperty('user_type')){
if(data.user_type==2){
employeeDetails(data.id, tab_id);
}else{
employee_details(data.id);
}
} else {
return false;
}
}
}
if i remove employee_details(data.id), this works perfectly.

How do I return a boolean value for a form's "onsubmit" attribute depending on the success or error of an ajax call?

If my form is defined as follows:
<form action="myAction" method="post" id="input" target="_parent" onsubmit="doThis();">
and doThis() is part of the following script:
var result = false;
function doThis() {
var myUrl = 'http://somewebsite.com/SomeWebservice/Webservice?args1=AAA&callback=?';
var status = false;
$.ajax({
url : myUrl,
type : 'get',
dataType : 'jsonp',
success : function(res) {
onSuccess(res);
},
error : function(e, msg, error) {
onError(e, msg, error);
}
});
return result;
}
function onError(e, msg, error) {
// do stuff if error
result = false;
}
function onSuccess(res) {
// do stuff if successful
result = true;
}
What I'm expecting is that if the ajax call is successful, onSuccess will set result to true, then doThis will return true and the form will submit. However, this does not happen. In fact, nothing happens.
My suspicion is that since the ajax call is asynchronous, doThis already returns a value (false) before the ajax transaction completes, so the return is always false. If that's the case, how do I modify my code so that it returns true or false depending on whether the ajax call is successful or not?
I think I can set async to false, but I keep on reading that callbacks are a better way to code than doing "async : false" --- so I was wondering what the best solution for this is.
EDIT:
I've put the following alerts in the onError and onSuccess functions:
function onError(e, msg, error) {
alert(e+" - "+msg+" - "+error);
result = false;
}
function onSuccess(res) {
alert("success");
result = true;
}
And running my code confirms that the logic passes through onSuccess.
Success is an AJAX event which is trigged after the AJAX completes http://api.jquery.com/Ajax_Events/ . So, what you are expecting is correct. Try adding some alerts to your code to see what each function is returning. like :
function onSuccess(res) {
// do stuff if successful
alert('Ajax success');
result = true;
}
r you sure that ajax request return success and go to function onSuccess(res) ?
you should add alert to know where the code goes. may be its goes to error : function(e, msg, error). alert what error msg saying?
I would suggest if possible you can go for Jquery Form Plugin. Instead of invoking an jquery ajax call
you can invoke ajaxForm or ajaxSubmitfunctions provided by that plugin. You can use these two functions just like an ajax call and it also supports success or error callback functions
Sample usage
$('#input').ajaxForm({
url: myUrl ,
success : function(response) {
// handle success
},
error : function() {
// handle error
}
});
Remove 'onsubmit' property.
<form action="myAction" method="post" id="input" target="_parent">
Instead use 'onclick' property. let's say your form is submitted by button or html element.
call $('.YourFormSubmitElement').onclick('doThis'). Note that if your has multiple form submission elements use class selector else if it is one use id selector.
Use the below function to submit the form.
function doThis() {
var myUrl = 'http://somewebsite.com/SomeWebservice/Webservice?args1=AAA&callback=?';
$.ajax({
url : myUrl,
type : 'get',
dataType : 'jsonp',
success : function(res) {
$('#input').submit();
}
});
}
I think this should fix your problem.

Post return values with AJAX?

I am using Code Igniter and I have the following Javascript function in my View. I have tried to echo values such as "error" from my handler function in the controller, but the "success" code is always ran in this function below instead.
Do I use echo or return to respond to the AJAX post? What value do I return for success and failure?
<script>
function removeDatacenter(id)
{
var cfm = confirm("Do you wish to delete this datacenter?");
if (cfm==true)
{
$.ajax({
type: "POST",
url: "<?=base_url()?>datacenters/remove_handler.php",
data: { id: id },
success: function(result)
{
document.location.href = document.URL + "?result=success";
},
error: function(result)
{
document.location.href = document.URL + "?result=failed";
}}
);
}
};
</script>
The success-method runs if the ajax-request was successfully sent to your script. It does not say anything about what the request returned.
If you simply do echo "error"; in your PHP-script, you can check the value in the success-method like this:
success: function(response) {
if (response == "error") {
document.location.href = document.URL + "?result=failed";
}
else {
document.location.href = document.URL + "?result=success";
}
}
Edit: People tend to use json_encode in the PHP-code and decode the json-string to an object in the javascript-code. That way you can send more structured data from your script.
Any text you echo will be seen, by AJAX, as a success. Even if it's the word "error". In order for you to trigger the Javascript error handler, you need to trigger some sort of actual HTTP error. If you're just trying to trigger an error for testing purposes, you could throw an exception in your controller. Or point the AJAX request to a URL that doesn't exist on your server (then you'd get a 404 error).
By the way, the error callback you have in your Javascript is slightly off on the API. It might not matter depending on what you do in the error handler, but here's the full call:
error: function(xmlHttpRequest, textStatus, errorThrown) {
//handle error here
}

setTimeout doesn't start until I stop the page

On the event of a form submit, I have a jquery ajax function that queries for the amount of data uploaded from a file that I can use in making a progress bar. This is my js file:
var submitted = '';
var counter = 0;
$('#webfileuploadform').submit(function(){
if(submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
update_progress_bar();
function update_progress_bar(){
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
counter ++
console.log('hit success ' + counter);
},
complete: function(jqXHR, status){
if (status == 'success'){
console.log('hit complete', status == success')
} else {
console.lot('hit complete', status == something else')
}
}
});
setTimeout(function(){update_progress_bar()}, freq);
}
submitted = 'submitted'; // marks form as submitted
});
So, the user will use the form to select the file then click submit. This all happens just fine. The form submits, the file is uploaded, and the progress shows just fine when I open my ajax view in a separate tab and keep refreshing it. What I don't understand is why the update_progress_bar function runs once until I stop the page. I'll upload a file but until I click the 'x' on my browser I won't get any of the 'hit success' in my console. After I hit stop, the console spits out the 'hit success ' plus the counter. But I shouldn't have to hit stop to do this. I need this to work when the file is uploading.
Any ideas what my problem is?
**
EDIT
**
Not sure if it makes a difference, but I am doing all this on a django development server. Which I think shouldn't have a problem with two XMLHTTPRequests in the same session.
Try this:
var $submitted = '';
$('#webfileuploadform').submit(function(){
if($submitted == 'submitted') return false; // prevents multiple submits
var freq = 1000; // freqency of update in ms
update_progress_bar();
function update_progress_bar(){
var progress_url = '/upload_progress/' + $('#id_progress_id').val(); // ajax view serving progress info
$.ajax({
dataType:"json",
url: progress_url,
success: function(data){
console.log("hit success");
},
complete:function(jqXHR, status) {
if (status == 'success') {
setTimeout(update_progress_bar, freq);
}
}
});
}
$submitted = 'submitted'; // marks form as submitted
});
As it stands, the code looks good to me. I would add some more console logging to make sure the ajax call is returning with the status you expect:
complete:function(jqXHR, status) {
console.log('got to complete, status: ', status);
if (status == 'success') {
console.log('status is success, calling setTimeout.');
setTimeout(update_progress_bar, freq);
}
}
In the ajax function I set the async setting to false:
$.ajax({
async: false,
...
});
This has solved the problem. I have no idea how. From what I understand, this setting forces the ajax request to wait until all other http requests are finished before allowing it to continue. With that being the case, I have no idea how this works. I'll keep from answering my own question in case someone knows why this is working this way...

PHP/ Ajax/ jQuery - Equivalent for my code

I have the following code and would like to use jquery to make it simpler:
var auctionBidAjax;
function auctionBid(auction_id) {
auctionBidAjax=GetXmlHttpObject();
if (auctionBidAjax==null) {
alert ("Your browser does not support XMLHTTP!");
return;
}
var url="/cms/ajax/auctionBid.php?auction_id="+auction_id;
auctionBidAjax.onreadystatechange=function() { auctionBidReady(auction_id); };
auctionBidAjax.open("GET",url,true);
auctionBidAjax.send(null);
}
And...
function auctionBidReady(auction_id) {
if (auctionBidAjax.readyState==4) {
if (auctionBidAjax.responseText == "Bid Placed") {
document.getElementById('auctionBid' + auction_id).innerHTML=
"Place Bid";
userBids();
} else if (auctionBidAjax.responseText == "Not Logged In") {
popupCentre('popupLogin');
popupLoad('popupLogin');
} else if (auctionBidAjax.responseText == "No Bids"){
popupCentre('popupNoBids');
popupLoad('popupNoBids');
}
}
}
My PHP script adds a bid etc and echos the responseText.
You've tagged this question as jquery so you can use $.ajax():
function auctionBid(auction_id) {
$.ajax({
url: "/cms/ajax/auctionBid.php",
type: "GET",
data: {
auction_id: auction_id
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// act appropriately
},
success: function(data, textStatus) {
// do whatever
}
});
}
If you didn't need an error handler you could use the simpler form of $.get() instead:
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.get(url, { auction_id: auction_id }, function(data, textStatus) {
// do whatever
});
}
I actually prefer not to use error handlers. It's a little uglier than it needs to be. Use that for actual errors. Things like "not logged in" could be handled by the success handler. Just pass back a JSON object that contains the required information to tell the user what happened.
For this you could use the $.getJSON() shorthand version.
function auctionBid(auction_id) {
var url = "/cms/ajax/auctionBid.php";
$.getJSON(url, { auction_id: auction_id }, function(data) {
if (data.notLoggedIn) {
alert("Not logged in");
}
...
});
}
To return some information as JSON from PHP use json_encode() and set the MIME type appropriately:
<?php
session_start();
header('Content-Type: application/json');
echo json_encode(array(
'highBid' => get_new_high_bid(),
'loggedIn' => $_SESSION['loggedIn'],
));
exit;
?>
I'm making assumptions about your login system so the above is a gross simplification.
Return that to a $.getJSON() callback and you should be able to do:
alert(data.highBid);
alert(data.loggedIn);
JQuery.get is what you need
http://docs.jquery.com/Ajax/jQuery.get

Categories

Resources