The code below is very simple. Basically, if variable "ret" returns a value and if the value is "fail" it should post Alert:"Trigger 2". However, the problem is the IF statement. It triggers the Alert:"Trigger 1" and when the conditional statement comes up, it skips it.
I'd like to know if I'm doing something wrong. Thank you.
$(function() {
var body = $(document).find("body");
body.on("submit", "#form-user-profile", function (e) {
var data = $(this).serialize();
var url = $(this).attr("action");
$.post(url, data, function(ret) {
alert("Trigger 1"); // Triggers alert
if (ret == "fail") {
alert("Trigger 2"); // does not trigger alert
}
});
return false;
});
});
If the response actually is fail then most likely the problem is some whitespace surrounding the response, causing the if statement to evaluate to false. This can be solved by trimming the response:
if ($.trim(ret) == "fail") {
If the code is actually running, you should be able to view response headers from the Post URL using Chrome or Firefox dev tools. That should give you what the actual response is and help you debug the answer, I imagine its simply returning something close to what you have, but not exactly what you have.
Related
I am wondering is it a good practice to make an ajax in an ajax callback function (could be called nested ajax calls?) ? Anyway here is my example
ajax.js
$(document).ready(function() {
$('#button').click(function() {
var string = 'some string';
$.post('ajax-call.php',
{
string: string
}, function(result) {
if(result == 'success') {
// Second ajax call if result returned is success
$.post('second-ajax.php',
{
variable: 'Some Variable'
}, function(second_result) {
if(second_result == 'yes') {
// Do some thing when the second result returned 'yes'
} else {
// Alert error or something
}
});
} else {
// If first result is not success, show a message
}
});
});
});
So basically I have two separate php file that is called on different time, if the first ajax call returned 'success' then proceed to call the second ajax call. Or should I be using one ajax call, one php script, and decide what to do depending on the result of callback ? example below.
ajax2.js
$(document).ready(function() {
$('#button').click(function() {
var string = 'some string';
$.post('ajax-call.php',
{
string: string
}, function(result) {
if(result == 'success') {
// Do something
} else if(result == 'unsuccessful') {
// If first result is not success, show a message
} else {
// Show error message
}
});
});
});
*Note: both php script are quite a heavy and long script which the first script is codes for validating the ajax call, and if everything is validated correctly, proceed to second ajax call to process the datas into database and so on. The first example will make the script much cleaner and neater, but I am wondering if it is good practice to use nested ajax like that ?
All suggestions and comments are greatly welcome. Thank you in advance for enlightening me on this.
Answering the question:
If both ajax calls are two different services and the second call depends on the first response, I'll do it.
If they are standalone services, I'll work with promises and do the callback when both are resolved.
Maybe is not focused on the question itself, but I see weird to make two server calls for just one real action (the second one).
What I'll do is to make just one call. If the validation doesn't pass, return the error. If it passes, call the other php on the server side and return a vlid response to the client.
Server should do the same job, but you save one data transmission from client to server.
That's just an opinion. I hope it helped you.
Currently I've been stuck on this code for almost two days now looking up everything I can on it but nothing I've tried has quite panned out, this could partly be due to me implementing it incorrectly or something else, but I figured I would finally ask. I should start by saying that I'm inside of a fancybox. The value of true that I want bIsError to be, shows up in console.log, however window.alert shows me that it's set to false. I did notice that the value changes once I run through my code. For example - If the username is incorrect it returns false then sets bIsError to true and displays an error message. However I just need it to return true and then give the error so that my code works. Anyways, here's my code, thanks for any feedback anyone will have as well, I really appreciate it.
if (typeof bFirstLoginPrep == 'undefined') {
var bFirstLoginPrep = true;
}
if (typeof $ != 'undefined') $(function () {
$(".ajaxformsubmit").unbind("click");
$(".ajaxformsubmit").click(function (event) {
setTimeout("lfSubmitForm()", 100);
return false;
});
});
function lfSubmitForm()
{
$form = $(".ajaxformsubmit").parents("form");
response = $.ajax({
url: $form.attr("action"),
type: "POST",
async: false,
data: $form.serialize()
}).responseText;
var responseList = false;
if (responseList == <%=LCase(bisError)%>) {
lfLoginSuccess();
} else {
$("#fancybox-inner").html(response);
$.fancybox.resize();
}
}
DinoMyte
<%=bIsError%> gives you the value of an instance server-side variable. If you are updating it via Ajax, it wouldn't work because you are probably making an ajax call to a pagemethod which is declared as static and static methods cannot manipulate the instance members of the page. In order to make it work with ajax, you need to return bIsError as part of the ajax response.
Amos
Yes, as DinoMyte says. Also you could set blsError as a session variable in this script before it is sent to the browser and then the script that the ajax calls can read it server-side.
I have two forms ('table' and 'fields'). The 'fields' form is supposed to pre-populate with options depending on the choice made in 'table', by making an Ajax request.
The data is returning perfectly and actually prepopulates the second form (like it should) if I pass a cut-and-paste example of some returned data to a local variable (see commented line).But for some reason it won't work on the returned object??
Any advice would be appreciated as I am very new to JavaScript and am probably missing something blatantly obvious! I am using the following code:
$(document).ready(function() {
$('select#table').change(function(){
$.getJSON("/ajax_get",{id: $(this).val(), ajax: 'true'}, function(data) {
//var data = [{"optionValue":"address", "optionDisplay": "address"},{"optionValue":"latitude", "optionDisplay": "latitude"},{"optionValue":"longitude", "optionDisplay": "longitude"},];
var $persons = $('#fields').empty();
$.each(data, function() {
$persons.append("<option value=" + this.optionValue + ">" + this.optionDisplay + "</option>");
});
});
});
});
Here's a simplified version of your call that should help you figure it out quickly:
$.getJSON("/ajax_get",{id: $(this).val(), ajax: 'true'}, function(data) {
try {
typeof(data.somethingYouExpect);
/* do your on success work here */
} catch (e) {
alert('There is a good chance the response was not JSON');
}
});
Even when using the regular jQuery $.ajax call, it's important to check to be sure the returned response is in the form you expect. This is as simple as setting a variable like success in your response as true. If you did that, the above example becomes something like this:
var jqxhr = $.getJSON("/ajax_get",{id: $(this).val(), ajax: 'true'}, function(data) {
try {
typeof(data.success); // Will throw if success is not present
if (success == true) {
/* handle success */
} else {
/* handle a request that worked, but the server said no */
}
} catch (e) {
/* The actual HTTP request worked, but rubbish was returned */
alert('There is a good chance the response was not JSON');
console.dir(jqxhr.textResponse);
}
});
Here, we remember the object returned by the $.getJSON call (which is just a shortcut to $.ajax), which allows us to view the actual response sent by the server. I'm willing to bet it's a 404, parser error or something of that sort.
For most things, I usually just use $.ajax mostly out of personal preference, where the error callback passes the xhr object to a common function to examine (did the request return 200? etc). If something explodes, I know exactly what went wrong by briefly looking at the console and can disable debug output in one place.
I've gotten my form to submit via PHP but I'm struggling a bit with the AJAX. Upon submission, the error always comes up as if res is set to false rather than true. I've tried toying around with the code and searching for my own answer because I do want to learn, but I'm not finding what I need.
May you please point me in the right direction as to what I've done improperly?
Thank you so very much!
The code for your reference:
$('#contact_form').submit(function() {
var this_form = $(this);
$.ajax({
type: 'post',
data: this_form.serialize(),
url: 'scripts/send_email.php',
success: function(res) {
if(res == "true") {
$(this_form)[0].reset();
$(".notice").removeClass("error").text("Thank you for contacting us!").addClass("success").fadeIn("fast");
} else {
$(".notice").text("Please check all fields and try again.").addClass("error").fadeIn("fast");
}
}
});
});
try to ask for:
if(res == true)
instead. Also a good way to avoid this kind of problems is to debug your javascript via firebug or the chrome debugger, if you are using chrome you could add this line to your code:
debugger;
if(res == "true")
and the javascript will stop there so you can inspect the variable and see what's happening. you can open it by going to "options --> tools --> developer tools --> scripts".
Hope this helps :)
In your send_email.php file, echo "success" if it succeed.
Then modify your AJAX call like so :
success: function(data) {
if (data == "success") {do stuff} else {do failure stuff}
}
It appears that your truth comparison is returning false due to the value that res represents. You are checking to make sure it is a string with the value of "true". If not, then trigger else code.
Your success property will only be executed if the AJAX transmission was successful. You will want to set the comparison check to the desired output of send_email.php, i.e. 'Success!' or 'Failure!' to indicate the proper handling.
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn.
See docs for additional information for handling AJAX requests in jQuery.
success: function(res) {
if (res == "Success!") {
$(this_form)[0].reset();
$(".notice").removeClass("error").text("Thank you for contacting us!").addClass("success").fadeIn("fast");
} else {
$(".notice").text("Please check all fields and try again.").addClass("error").fadeIn("fast");
}
}
I have a login form which appears at the top of all of my pages when the user is logged out. My current jQuery/javascript code works in Firefox 3 but not IE 7. The code queries a page which simply returns the string "true" or "false" depending on whether the login was successful or not. Inside my $.ready() function call I have the following...
$('#login_form').submit(function() {
var email = $('input#login_email').val();
var pw = $('input#login_password').val()
$.get('/user/login.php', { login_email: email, login_password: pw }, function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
});
alert('called');
return false;
});
In FF, I am successfully transferred to the intended page. In IE, however, the below alerts "called" and nothing else. When I refresh the page, I can see that I am logged in so the $.get call is clearly going through, but the callback function doesn't seem like its being called (ie. "get succeeded" is not popping up). I also don't appear to be getting any javascript error messages either.
Why isn't this working in IE?
Thanks
EDIT: Since a couple people asked, whenever I enter a correct email/password or an incorrect one, nothing in the callback function happens. If I manually refresh the page after entering a correct one, I am logged in. Otherwise, I am not.
EDIT 2: If I alert out data in the callback function nothing happens in IE (I do not get an alert popup). In FF, it alerts true for valid email/pw combos and false for invalid ones. I am using jQuery 1.3.2.
EDIT 3: Ok, guys, I tried R. Bemrose's thing down there and I'm getting a "parseerror" on the returned data. I'm simply echoing 'true' or 'false' from the other PHP script. I also tried 'yes' and 'no', but that still gave me a parse error. Also, this works in Chrome in addition to FF.
In your response type use:
header("content-type:application/xml;charset=utf-8");
As stupid as this sounds... perhaps IE7 is being anal retentive about the missing semicolon on the var pw line?
Probably not, but the only way I can think of getting more information is to convert it to an $.ajax call in order to add an error hook and see which error type it think is happening. Oh, and to check out the exception object.
$.ajax({
type: 'GET',
url: '/user/login.php',
data: { login_email: email, login_password: pw },
success: function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
},
error: function(xhr, type, exception) {
alert("Error: " + type);
}
});
If the error type is parse, IE may be complaining because the data coming back has extra commas at the end of comma separated arrays/lists.
IE uses cached data for get requests. Maybe that's your problem? What happens if you try different user id, password?
In any case, isn't it a better idea to send password in POST? :)
I'm am having a similar problem with the following code:
var listOrder = $(this).sortable('toArray').toString();
var otherVariable = whatever
$.get('process_todo.cfm?method=sortToDos', {listOrder:listOrder,otherVariable :otherVariable });
The variable displays through an alert as 'test_123,test_456'. I can hard code the same values and it does not fail. It must have something to do with the 'toArray'? I have been trying to debug this one thing for hours. Works perfectly in Firefox, Safari and Chrome... of course!
Instead of:
if(data == 'true')
try:
if(data)
then in your server just return either a 1 (or true) and a empty value.
What you've posted (at least after Edit 2) looks good. I think the problem is in what you haven't posted.
First, have you checked your server logs to ensure that it's sending back what you presume?
If so, I'd recommend dropping the submit mechanism and using a 'button' type with an 'onclick' handler, and not 'submit' button w/a 'onsubmit' handler...
<input type="button" id="login_submit" value="Login" />
Then switch the submit handler:
$('#login_form').submit(function() { ... });
from the form to the button with:
$('#login_button').click(function() { ... });
If that doesn't help, can you post the HTML for the form, too?
[Edit 3] - try adding the 4th 'type' parameter of "text" to the $.post() call.
Have you used Fiddler to have a good look at what's actually being transferred? (http://www.fiddler2.com)
if you are testing/checking your script in local machine then you will not see any thing in any version of internet explorer because IE on localmachine send datatype as text and not xml and in your case again its matter of datatype not compatible with your document datatype so it worth checking if your datatypes are matching
as far as xml goes solution is here
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
you may check this and find some inspiration :)
salman