I have a form which sends data to a CRM. If I create a simple HTML form and send the data to the server it will refresh my webpage and show the text:
{"success":false,"error":{"message":"<whatever the error is>"}}
or
{"success":true,"result":"ok"}
After styling the form and integrating animations and validations and stuff everything still works perfectly. Now the data is sent by using http://jquery.malsup.com/form/#getting-started. The server receives it but the user has no idea whether it did or not.
Using this jQuery form plugin or some other plugin you might want me to use(or even code) please help me display text inside a div whether the operation was successful or not, depending on the server's response.
I have only tried to display the response using the examples provided here: http://jquery.malsup.com/form/#ajaxForm but I have failed until now.
Here I've put together a JSfiddle with some form fields and the jQuery form plugin I am using in order to send the data to the server: http://jsfiddle.net/n78p9/1/.
I hope someone will be able to show me what I did wrong or show me another way of doing this.
Thank you!
EDIT #Arun: so it looks like this:
submitHandler: function(form) {
$(form).ajaxSubmit({
target: '.optional',
resetForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('Thank you for your message! Our team will contact you in the shortest possible time.')
}
});
}
I am definitely on the right way, but there is a problem: the error alert actually shows when the response is successful. I do not understand why. I have intercepted the POST request through a local proxy and re-sent it through the server and the server sent back this:
{"success":true,"result":"ok"}
But the script considered it an error. That is why I have inserted that text into the error:alert field:D.
What might be the problem?
Try using the callbacks provided by the library
var options = {
target: '#response',
success: showResponse,
clearForm: true,
success: function(responseText){
var result = jQuery.parseJSON(responseText);
if(!result.success){
alert(result.error.message)
}
},
error: function(){
alert('some error')
}
};
$('#contact-form').ajaxForm(options);
Related
Scenario: I have a 4 input forms [A-D] then i have checked the A and B.
i want to get it from the other page but i don't know how.. i was trying to search for other people post to learn but there is much a lot of tutorials about ajax is on posting select and input tags.
can you please give me an example about radio buttons
when i'm going to checked the value i want and to submit it clicking the button
to send an ajax xmlhttpequest to other script.
thank you in advance dude :)
i'm using jQuery to post the value of the option tag i have selected
then it will call back to the div to show a table with a list of radio buttons
i have already tried to get the data by pushing all the values of checked data into a set of strings of an array by using jQuery and it was successful :)
but it doesn't response to the other page (Admin) what user have submitted.
and that's why i need to refresh it to load and see what the data had user submitted. (different user/session).
i was wondering if i could use xml httprequest to do a real time interaction with the user-admin.
that's why i was hoping if anyone could give me an example how to get the values of radio buttons i have checked to post it to the other script and insert in the db.
sir.
In the initial page, you can use this:
$.ajax('/WHERE_DATA_IS_SENT', {
data: $('input[name=name_of_your_radiobutton]:checked').val(),
success: function (data) {
// Do something... maybe redirect the user to the other page?
},
error: function () {
alert('Data could not be sent to the server');
},
type: 'POST'
});
Then in the other page, you can use jQuery ajax again to get the data from the server:
$.ajax('/WHERE_YOU_GET_THE_DATA', {
success: function (data) {
$('ELEMENT_WHERE_DATA_GOES').html(data)
},
error: function () {
alert('Data could not be received from the server');
},
type: 'GET'
});
I have an HTML form. I am already doing a client side HTML.
<form id='myForm' onsubmit='return myFormValidation()'>
...
</form>
Now, in myFormValidation function, after making sure the client side is OK, before really submitting the form, I want to do also a server side form validation.
I am using JQuery. So,I changed my function to something like this:
function myFormValidation(){
//first, client side validation
...
//then, server side validation
$.post(url_of_server_side, $("#myform").serialize(), function(json) {
data = JSON.parse(json);
if(!data.ok)
{
$("#msg").text("some error");
}
else
{
$("#myForm").submit();//Oops!
}
});
return false;
}
But the "submit" function of form behaves like a recursive function and tries to validate the form again!
Should I disable the validation function before calling submit? Or, I guess, there is a better way for my problem (which is slightly or even totally different than this)?
If you need server side validation you should extend your "Save" enpoint to support correct response status codes and do not use separate "Validation" url. Use single url with different response types:
200 (Success) - data was saved successfully
400 (Bad request) - input data was incorrect. As response message you can include "validation result" message which you will display to user.
So your code can looks like
$.post(url_of_server_side, $("#myform").serialize())
.done(function() {
//show some success confirmation or redirect to main page
}).fail(function(xhr, status, error) {
$("#msg").text(error.message);
});
I would suggest, if all data is OK, the server-side script to perform the action that you want, e.g. saving to database. That way, you will not need a second post of the form in case everything is correct.
If something is wrong, then obviously, the checks must take place the second time as well.
I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes
onSubmit: function(invalid, e) {
e.preventDefault();
$('#invalid')
.show()
.toggleClass('valid', ! invalid)
.text(invalid ? (invalid +' invalid fields') : 'All good!');
if (!invalid) $.post('register.php', this.$form.serialize(), function(response) {
}, 'json');
}
This is my post function under .When I click submit the text 'All Good' comes but the page doesn't refresh or post the details to the register.php page.
You seem to be fundamentally misunderstanding how AJAX works. You're expecting the page to refresh, but the code you're using explicitly tells the page not to refresh. First, there's this:
e.preventDefault();
This does exactly what it says, it prevents the default event. Assuming this is on a form, it's explicitly preventing the form from submitting. Then you have your AJAX request:
$.post('register.php', this.$form.serialize(), function(response) {
}, 'json');
As you've confirmed in FireBug, this sends a POST request to the server. But... you're not doing anything with the response. Your function is empty:
function(response) {
}
So... what do you expect to happen? An empty function... doesn't do anything. You can confirm in FireBug whether the response is what you expect it to be, but that's an entirely separate issue. Whatever the response is, whether it's correct or not, isn't going to display on the page if you don't actually display it. Take a look at the examples in the documentation:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
The response is placed in the $(".result") element(s). In this code they're displaying the response. If you want to see the response, you have to display it somewhere as well.
Overview:
I'm using the JQuery Form Plugin to send Form Data to a remote file via AJAX. The File then processes the form data and inserts it into the MySQL Database.
Problem:
The Problem is, however, when I want to run code on a successful add, (usually completed using the "success" option, it never runs. Doing further research I found that I needed to send back "responseText" to make the function under "success" run.
Questions:
1) Is this true?
2) How do I go about sending back responseText?
3) (If number on is that it is not true) How do I get the function under success to run?
A few code Snippets:
JQuery (Using the JQuery Form Plugin):
$("#form1").ajaxForm({url: 'submit.php', type: 'post', resetForm: true, success: function () { $('#new-paste').modal({show: false}) }});
I can provide the contents of the remote file (submit.php) if needed.
Thank you in advance!
Change your success to:
function(response) {
$('#new-paste').modal({show: false});
alert(response); // response is the output from the php script it submitted to.
}
Hope this helps.
Alright, so I found the solution.
The Script had to be included on the page itself, not in a remote .js file.
so:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
Should be included in the head.