Mootools ajax form response - javascript

I'm trying to send a form with mootools and depending on the response from the php script do such or such thing. The thing is I fail to be able to use conditional statements inside of the onComplete part of the code.
I'm missing something really obvious probably, please help me :)
$('formName').addEvent('submit', function(e){
e.stop();
var req = new Request.HTML({
url : 'phpUrl.php',
data : $('formName'),
update : $('modify-me'),
onComplete: function(){
$('formName').reset();
if($('modify-me').get('text') = "1"){
alert("succeed");
}else{
alert("failure");
}
}
}).send();
});
This was my lame attempt to use the php response in the code, but of course it didn't work.
Needless to say I'm new to all this asynchronous client-server communication stuff, but I'm really intrigued by it.

You are assigning in your if statement (single =), not checking equality (==). Change the line
if($('modify-me').get('text') = "1")
to
if($('modify-me').get('text') == "1")

Sorry guys, maybe I'm late... I'm working on Mootools 1.2.4 for the client side and on PHP for the backend. This is the way I submit forms and get response from the server...
$('myFormID').set('send', {
noCache: true,
onRequest: function(){
// show some rotating loader gif...
},
onComplete: function(response) {
// hide the loader gif...
objJson = JSON.decode(response);
if(objJson.success){
// do your success stuff...
alert(objJson.msg);
} else {
alert(objJson.msg);
}
},
onFailure: function(){
alert("Request Aborted.");
}
}).send();
In my case the form submit is triggered by a button, but could be whatever... let's look at the server side (I use PHP but any other language is good)
if($somethingWentWrong){
echo json_encode(array("success" => false, "msg" => "Check your form."));
} else {
echo json_encode(array("success" => true, "msg" => "Data saved."));
}
after all the server-side checks and validations (and maybe an Update on a MySql batabase) I just return a Json array (that's whay I have a JSON.decode(response) on the client-side-earth) and then just check the "success" key to discover if the submitting succeded on the server-side-moon. I just add a small message that I display in an alert. Obviously I could use the JSON array to send back a lot more data to the client, but in this case is enough. Hope this helps and please let me know of better solutions.

Related

Location: Header not working for one particular trigger

Okay, so, I have a PHP and JS-based webapp that does mostly what it's supposed to do. This being said, before I show any code, bear in mind a few things.
1.)The top two location headers inside the 'if' loops work as intended.
2.)In the development tools in Chrome, the location is in the header for this request.
PasteBin to my code here.
In my JQuery (defined in html head), we see a button name "subAll2", which is supposed to post the intended data, and do a redirect using aforementioned JQuery. The other two redirects work via intended forms. Why does this one not work?
$('#subAll2').click(function() {
var action = $('#frmUser').attr('action');
$.ajax({
url : action,
type : 'POST',
data : $('#frmUser,
#frmUser2').serialize()+"&butSubmitAll=submitAll",
success : function() {
window.location.replace(action);
}
});
return false;
});
Obligatory codeblock for requirements. Please check the PasteBin.
I found the answer. In the JS, replace the success function with
success : function(data) {
if (data == "success")
windows.location = "list_user.php";
else
alert("Form didn't go through.");
}
And instead of
header("Location:list_user.php");
Replace with
echo "success";

Should I validate response data in jQuery's ajax success handler?

Let's assume I have a post AJAX call and I want to put returned data into some HTML elements.
$.post(settings.url, function(data) {
$('#someElement').text(data.someData1);
$('#someElement2').text(data.someData2);
});
I'm a back-end developer and it's natural for me that I have to do server-side validation of any piece of data coming from user. Although it's the opposite situation, the code above feels a little bit wrong for me (not validated outside data). But on the other hand, I know what I'm returning from the server.
The question is if is it fine to trust that data returned from (also mine) back-end application will have expected structure, or should I validate somehow every data coming server?
Additional question is if there is some nice method to do such validation? Manual validating of existence of every piece of data seems to be a pain in the neck. Especially for more complex data structure.
Just during writing this question an idea came to my mind. I could use $.extend() just like it's commonly used for setting default options while writing modules/plugins. Something like:
$.post(settings.url, function(data) {
var trustedStructure = $.extend({
someData1: $('#someElement').text(),
someData2: $('#someElement2').text(),
}, data);
$('#someElement').text(trustedStructure .someData1);
$('#someElement2').text(trustedStructure .someData2);
});
That way I could have trusted data with additionally current data as default or any other if I want.
Edit:
Forgot to note. I'm talking about pure JSON data responses. No HTML etc included.
Generally you don't validate the response data, as you said before, the data is returned from your own back-end. What you really need to do is to ensure that you have a proper way to handle exceptions or errors with the information coming from the server.
If you're returning an exception from the server you should have a way in the client-side to figure out that if an error or not.
i.e. returning a specific code like a Rest API or having a JSON structure like this:
// Success
{
"error": false,
"data": {
...
}
}
// Exception
{
"error": true,
"message": "Username already taken",
"type": "warning"
}
If you always return a 200 OK status code:
$.ajax({
...
success: function(response) {
if (response.error) {
alert(response.error.message);
} else {
document.querySelector('#field').value = response.data.text;
}
}
});
The HTML Response Codes are useful when you use promises, you can return a 200 OK for the primary flow (success, done), and 4XX or 5XX if something unusual happen (fail):
$.ajax({
url: 'example.php',
...
})
.done(function(response) { alert(response.data); })
.fail(function(error) { alert(error.message); })
.always(function() { clearFields(); });
Does the data returned from your server contain DOM Elements?
If it doesn't and is a pure text return, you can use a textarea to parse incoming data like this:
var textArea = document.createElement('textarea');
textArea.innerHTML = data;
data = textArea.textContent;
Just try it out and let the server send some <p>, <img> or <script> Elements

Is it a good practice to make ajax call after ajax callback?

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.

Can I trigger my Html.ValidationMessageFor with jquery and have it display some string I define in JQuery?

If I have a validation tag in my asp.net mvc application for a text field called search, can I plug into it using jquery/javascript to get it to trigger if certain logic is performed? How would I do that?
It looks something like this
#Html.TextBox("SearchQuery", other stuff here, other)
#Html.ValidationMessageFor("SearchQuery")
Say I want to trigger the validation message to show if this occurs
$('form').submit( function (e) {
e.preventDefault(e);
var results = GetLocation();
if (results) {
this.submit();
} else {
// trigger validation message and display "can't find results"
}
});
Please note that I don't think I need to validate here, I just want to show a message where the validation message would be if I did validate
As far as i understand your question, for custom messages coming from server you need to send the object to server and then get the response from it.
You can perform it with an ajax call for example:
$.ajax({
url : 'example.com',
type: 'POST',
data : results,
success:function(datafromserver)
{
$('.resultState').html(datafromserver);
}
});
Another thing if do validation first in the client and then send (and check again in server), in this case remember var result can always be true if the getLocation functions returns anything (such as string , object etc...) so in this case print it with console.log and take a look if is it an object (f example: data.x === none or 'no coordinates' just evaluate it correctly and you can avoid ajax.
Hope helped!
Regards

AJAX Contact Form - Success and Failure Message

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");
}
}

Categories

Resources