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");
}
}
Related
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 am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.
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.
I am making an ajaxSubmit call to a web service, that will return XML.
When I make a call to the same service using XMLHttpRequest.send, the response is correct.
However if I use:
$(form).ajaxSubmit({
error: function _(response) {
$(iframeEl).remove();
config.error.call(scope, Thunderhead.util.JSON.decode(response));
},
success: function _(response) {
console.log(response);
$(iframeEl).remove();
var result = response;
config.success.call(scope, result);
},
iframe: true
});
This returns the correct XML response, but all tags have been transformed to lowercase.
I've checked the call in the Network tab in the developer console, and the case is correct in there, but when it is returned by the ajaxSubmit, it is lowercase.
Does anyone know what is causing this or how to rectify it?
Are you using Malsups jQuery form plugin
This plugin does a lot of toLowerCase transforms, I've not looked too closely but it does seem to lowercase the tag names of something, so this is probably your culprit.
I'd recommend refactoring to using a simple jQuery.ajax() call instead
$(form).on('submit', function(e) {
var url = $(form).attr('action');
e.preventDefault();
$.ajax( url, {
error: function _(jqXHResponse) {
// your code
},
success: function _(response) {
console.log(response);
// your code
}
});
This might be happening, because js is assuming xml as an answer. There is no difference for most xml-parsers which case is used in xml tag names.
I suggest trying to change response data type.
For example there is such option in jQuery.ajax method: http://api.jquery.com/jquery.ajax/ (named dataType). I would try using "text" dataType if case is really important.
Some further issues arose from this in the end, so just posting my eventual solution in case anyone else has this problem. I'm fairly new to javascript, so this might have been obvious to most, but it might help someone else out.
The success callback can actually take in 3 parameters, the third of which (arg2) is the actual response from the request, without any changes from the Malsups form plugin.
So in the end, the solution was simply to use this third parameter instead of the response parameter.
$(form).ajaxSubmit({
error: function _(response) {
$(iframeEl).remove();
config.error.call(scope, Thunderhead.util.JSON.decode(response));
},
success: function _(response, arg1, arg2) {
console.log(response);
$(iframeEl).remove();
var result = response;
config.success.call(scope, arg2.responseXML);
},
iframe: true
});
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.