Submitting form via ajax in jquery - php

i am having some problems with getting my form to submit. It doesnt seem like anything is being send, is their anything wrong with this code as javascripting isn't my strong point...
$("#send").click(function() {
var complete = true;
$('input#name, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#ffffff").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#ffffff");
complete = false;
}
});
if (complete == true){
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = '{"name":"'+name+'","sender":"'+email+'","subject":"'+subject+'","message":"'+message+'"}';
$.ajax({
type:"POST",
url:"contact.php",
data:$.base64.encode(data),
success:function(data){
data = $.parseJSON(data);
if (data.status == "success") {
$.fancybox.close();
}
}
});
}
});
There is also a live version of this in action which can be viewed over at: http://idify.co.uk, thanks :)

You can do it better.
$('form')
.submit(function(event) {
var form = $(this);
$.ajax({
url: '[url here]',
type: 'post',
data: $.base64.encode(form.serialize()), // $.serialize() - it gets all data from your form
dataType: 'json', // function in success callback knows how to parse returned data
success: function(data) {
if (data['status'] == true) {
// your code here
// e.g.
$.fancybox.close();
}
}
});
event.preventDefault();
});
Enjoy! :)

I got an error after submitting:
data is null http://idify.co.uk/javascripts/landing.js Line 25
It looks like the data was sent successfully and there was a response:
{"status":"error","responce":"No token parameter was specified."}
This should help you ensure you've got data in your success callback:
success:function(response) {
if (response) {
var data = $.parseJSON(response);
if (data && data.status == "success") {
$.fancybox.close();
}
} else {
// handle errors
}
}

Haha, thanks guys. I was silly enough not to include the variable that needs to be passed via the php file, got it sorted and it works like a dream, i ended up using the first solution as the form submission one wasnt working for me.

Related

Bringing back several variables into ajax form POST success as jQuery variables

I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery

Form Validation, problems with passing of argument and page redirection

So I'm creating this form validator with PHP and jQuery.
The PHP code will check through the form and then return an array with fields that contain errors. Example: {"email":1,"password":1}
But now I have concerns regarding if no errors were to be found. The problem here is that I've included "return false" in the end of the code to prevent page redirection. I've read that this is bad code practice but not found another way that works as intended.
The second problem is how to pass the o-array into the $('input').each function. Right now it will say that all forms are valid since nothing was passed. If I use $.post instead of $.ajax this scope problem doesn't appear for some reason.
jQuery:
$(function() {
$('#register').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0) {
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
return false;
});
});
Fist, why are you submitting a form when you really don't want to?! Use a button instead and make the AJAX request from its click handler.
$('#registerButton').click(function() {
var form = $('#register')
var data = form.serialize();
$.ajax(...);
});
"The second problem is how to pass the o-array into the $('input').each"
What is the problem here? If you have an each() inside a success callback, you can use the data parameter that is passed to the callback (or o in your case) in that each().
Try this
$(function() {
$('#submit_button_id').click(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
var ret = true;
$.ajax({
type: 'GET',
url: url,
async: false,
data: data,
success: function(o) {
console.log(o);
$('input').each(function() {
var msgId = o[$(this).attr('name')];
console.log(o[$(this).attr('name')]);
if (msgId > 0)
ret = false;
$('#listError').css('visibility', 'visible');
$('#listError').append('<li>' + $(this).nextAll('span.msg').eq(msgId - 1).text() + '</li>');
$(this).addClass('invalid');
} else if (msgId != 0) {
$(this).addClass('valid');
}
$('#listError').append('</ul>');
})
}
}, 'json');
if(ret==true){
$('#register').submit();
}
});
});

jquery post with $.ajax, how to avoid multiple post?

still looking for a solution but not find yet, I have a function to manage different forms on same/differents pages
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
after loaded the page and form with an input type="button" named SEND
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
$('form.standard').submit();
});
all the values reach a php page via POST that made all the things (validating, insert in db, update log...) and answer with 'OK' if all OK (so the form in the modal window is substituted with custom message and fade out) or... if there is an error, php answer with some text that js popups with an alert keeping the modal window open with the form.
It's all ok BUT, if php answer with an error, with second click of button SEND the post is sent 2 times.
And if I make another error on second send, and click again the send button, the post values is sent three time... and so on.
What can I do? Where is my error?
thanks.
Try excluding submit block:
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
//$('form.standard').submit(function(event){
// event.preventDefault();
//change 'this' to form.standard
var modalWin = $('form.standard').parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
// }
and after loaded page:
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
//excluding submit event
// $('form.standard').submit();
});
Because $.ajax {} with type:"Post" is already a submit process and then when script call submit then it re-submit.
Hope this right and help
Is it possbile that somewhere in your code you bind the submit event to the form everytime you get the data back from the ajax-request?
I can't check this in the code you submitted here.
Create a global variable as flag
var flag = 0;
and check this flag while posting and reset it after completed
function formStantardAction(correctAnswer,addCustomData){
**if(flag == 1){
return false;
}
flag = 1;**
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
**flag = 0;**
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I put some custom code at the beginning of your submit function - basically if a submit is in progress nothing should be done, but otherwise return an error message as usual.
var submitting = false; //initialise the variable, this needs to be out of the function!
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
if (submitting) {
return false; //if a submit is in progress, prevent further clicks from doing anything
} else {
submitting = true; //no submit in progress, but let's make one now
}
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}

Get JSON responce from ajax call to PHP script

I have been successful in returning the json responce from the ajax call to my php script that sends messages. When submitting data to the PHP script, if successful it should return a json string like the following...
{"status":"valid","message":"Your message was send successfully."}
I would like to check if the "status" equals valid and then show a div showing that the message has been sent. How would i go about doing this and this is the code i have so far...
$("#send").click(function() {
var complete = true;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#121212").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#121212");
complete = false;
}
});
if (complete == true){
var name = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = 'name='+name+'&email='+email+'&subject='+subject+'&message='+message;
$.ajax({
type:"POST",
url:"resources/includes/contact.php",
data:data,
success:function(data){
alert(data);
}
});
}
});
Thanks,
Nathaniel Blackburn
you can do it like this
$.ajax({
type:"POST",
url:"resources/includes/contact.php",
data:data,
dataType: 'json',
success:function(response){
if(response.status="valid"){
......
}
}
});
In your success callback function, add
data = $.parseJSON(data);
if (data.status == "valid"){
//do stuff
}
change your success function to look like this:
success:function(data)
{
jsonObject = JSON.parse(data);
alert(jsonObject.status);
}

Updating div using ajax not working correctly

Sorry but I know something similar to this has already been posted. I have tried every single resource out there and did my research and I still couldn't find out what is wrong with my code. I am using a Ajax Post with php. Everything seems to be working fine except for the fact that the div is not reloading on submit. After I refresh the page what I posted came up. Can someone please tell me what I am doing wrong.
js code:
$(function() {
$('.error').hide();
$('input.text-input').css({
backgroundColor: "#FFFFFF"
});
$('input.text-input').focus(function() {
$(this).css({
backgroundColor: "#C0DDFA"
});
});
$('input.text-input').blur(function() {
$(this).css({
backgroundColor: "#FFFFFF"
});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var dataString = '&email=' + email;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
return false;
});
});​
html code:
This is where I have my div.
<div id="div"> <?php \\database select query ?> </div>
I am new to this website sorry if I posted something wrong...
did you get any error in console (firebug/developer tools) ?
otherwise you can try below
check with alert
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
alert(data);//what you get here? are you getting "object" in alert? then you need to specify property or mention dataType
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
modified your code a bit see the comments, you should specify dataType:html (see the ajax part).
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#C0DDFA"});
});//focus ends
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});//blur ends
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
//var dataString = '&email=' + email; commented out
var dataString = email; //try insted this
//alert (dataString);return false;
$.ajax({
type: "POST",
dataType:'html', //or the appropiate type of data you are getting back
url: "../EdinburgCISD/Gorena/Gorena.php",
data: {email:dataString}, //in the php file do $email = $_POST['email'];
async:false, //not a good practice but you can try with it and without it
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
}); //ajax ends
return false;
});//click ends
});//document ready ends
update
see this fiddle you will get the idea http://jsfiddle.net/3nigma/LuCQw/ and the delay function is optional i have used it so that the effect is prominent

Categories