Running AJAX query to refresh div with php file - php

I'm currently working on a multi-step query form which can be found at: http://jsfiddle.net/xSkgH/47/.
I'm trying to submit the variables via jQuery AJAX (process.php will handle the processing) and refresh the div last-step with the div in the process.php called result. How can I achieve this?
I've so far managed to accomplish this using the jQuery form plugin by malsup (http://jquery.malsup.com/form/) and now need to using the jQuery AJAX method to accomplish it as part of a strict specification.
This is the code I had been using (with the jQuery form plugin):
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#result',
beforeSubmit: showRequest,
success: showResponse
};
// bind to the form's submit event
$('#task5_booking').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
// alert('About to submit: \n\n' + queryString);
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}
Many thanks!

Use jQuery.ajax to handle the last step:
http://api.jquery.com/jQuery.ajax/
else if (whichStep == 'last-step') {
$.ajax( {
url:'urltophp.php',
data: {}, // your data
dataType: 'json', //your datatype
type: 'POST', //or GET
success: function(r) {
//your callback here...
}
});
}
Edit:
$('#task5_booking').submit(function(e) {
$(e).preventDefault(); //prevent the default form submit()
var formData = $(this).serialize(); //serialize the form fields data...
$.ajax( {
url:'urltophp.php',
data: formData, // your data
dataType: 'json', //your datatype
type: 'POST', //or GET
success: showResponse
});
//$(this).ajaxSubmit(options);
//return false;
//});
});
Change this:
function showResponse(responseText, statusText, xhr, $form) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}
To this:
function showResponse(responseText) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}

use http://api.jquery.com/load/ .
it's like using .ajax, only easier and fits your requirements.
$('#last-step').load(url, data, function(){}) sends a post request, and fills the html content of 'last-step' with whatever the url printed out into the response html.

Related

preventDefault() on $.ajax complete [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm wanting to use AJAX to determine whether or not a form's values are acceptable to me (this is not form validation). The AJAX result will determine if the form is submitted or not.
Below, you'll see that I perform an AJAX call when the form is submitted and depending what is returned (either blank which is acceptable, or an error message which is not acceptable), I'd like to return true; or return false; the $("form").submit.
I suspect my trouble to be in the AJAX's success:. Please help me get the result out of the AJAX call so that I can do something like if (result == "") { return true; } else { return false; }.
WORKING:
$("form").submit(function(e) {
e.preventDefault();
var form = this;
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "")
form.submit();
else
alert(result);
}).fail(function() {
alert('ERROR');
});
});
ORIGINAL:
$("form").submit(function() {
var tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
success: function(result) {
alert(result);
},
error: function(result) {
alert(result); //This works as expected (blank if acceptable and error msg if not acceptable)
}
});
/*
if (result == "")
return true;
else
return false;
*/
return false; //this is here for debugging, just to stop the form submission
});
As the ajax call is asynchronous, you have to prevent the form from submitting, and then when a result is returned, you check if it matches the condition and submit the form with the native submit handler, avoiding the preventDefault() in the jQuery event handler :
$("form").submit(function(e) {
e.preventDefault();
var self = this,
tray = $('select[name=tray_id]').val();
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false
}).done(function(result) {
if (result == "") self.submit();
}).fail(function() {
alert('error');
});
});
use e.preventDefault(); to prevent the form from submitting, and then use this.submit() (isn't calling the jQuery .submit() trigger function, but rather the native <form> .submit() function) to submit the form.
$("form").submit(function(e) {
e.preventDefault();
var tray = $('select[name=tray_id]').val();
var form = this;
$.ajax({
type: "POST",
url: "modules/reserve-check.php",
data: {tray_id: tray},
cache: false,
complete : function(result){callback(result, form)}
});
});
var callback = function(result, form){
if(!result)
form.submit();
};

Ajax Validation intrupt the form submit on form submit event

Hi i have problem with form redirection to its action target, validation ajax interrupt the form redirection here is my code , all i just submit the post to form action location also redirect on that location.
$("form").submit(function(e){
jQuery.ajax({
type : "post",
url : "validate.php",
dataType : "json",
data : {email : 'example#domain.com'},
success: function(response) {
if(response.status == '1'){
//Email is valid want to continue form submit and redirect , but it is not
}else{
e.preventDefault();
//return false
}
}
});
})
You may need to create a separated function to submit your form as a callback of the validation ajax process and pass the serialized data to it, something like :
function submitForm(serializedData) {
jQuery.ajax({
ur: "{your form action processing file}",
type: "POST",
data: serializedData,
success: function (data, textStatus, xhr) {
console.log("form submitted "+xhr.status) // 201 if everything OK
// optionally reload the page
window.location.reload(true);
}
});
}
jQuery(document).ready(function ($) {
// validate form
$("#myForm").on("submit", function (event) {
// prevent form from being submitted
event.preventDefault();
// collect your form data to be submitted :
var serializedData = $("#myForm").serializeArray();
$.ajax({
url : "validate.php",
type: "POST",
cache: false,
dataType : "json",
data : {email : 'example#domain.com'},
success: function (response) {
if(response.status == '1'){
// email is valid so submit the form
submitForm(serializedData);
} // you don't need an else statement since we already used event.preventDefault() before the ajax call
},
error: function () {
console.log("ajax validation error");
}
})
}); // on submit
}); // ready
Notice we assigned a selector (#myForm) to the form we are processing.

refuse ajax submit if fields are empty jquery

Let's say I have a simple form. I use this jquery piece of code to get the result using ajax on my form page.
function sendquery()
{
$("#form").submit();
var url = "form.php";
$.ajax({
type: "POST",
url: url,
data: $("#form").serialize(),
success: function(data)
{
$("#output").html(data);
}
});
return false;
}
Quite simple. What I want now is to validate the form by adding a class, let's say "blank" to inputs with empty value, and don't allow the form to be submitted. It shouldn't be too hard, but whatever i've tried will just break my form.
How can I do it?
you need jQuery validate plugin , and ......
$(document).ready(function()
{
$('#formId').validate({
submitHandler:function(form)
{
$(form).ajaxSubmit({
success:function(response)
{
//do stuff on success
},
dataType:'json'
});
},
errorLabelContainer: "#error_message_box",
wrapper: "li",
rules:
{
name:"required",
category:"required"
},
messages:
{
name:"name required",
category:"category required"
}
});
});

jQuery Dynamic form submission and Ajax call

everything works, I get my json array returned in an alert, I just need to change the onSubmit event handler $('#city').submit(function() to something more dynamic that grabs the user input and runs the ajax call as soon as the user types the letters.
I'd recommend the keyup() event:
$("#term").keyup(function(e){
});
But you can also use the autocomplete function from JQuery-UI: autocomplete
Using autocomplete this would be:
$("#term").autocomplete({source: "/suggestjson", minLength: 2, select: function (event, ui) {
//do something when the user selects, by the way the value
//selected by the user is in: 'ui.item.value'
}});
Use
$('#city').change(function() {
var formdata = $('#term').val()
$.ajax({
url: "/suggestjson",
type: "GET",
dataType: "json",
data: {'term': formdata},
success: function (data) {
alert(data);
}
});
return false;
});
Or
$('#city').keyup(function() {
........
.......
});

AJAX loading message

I want to display a loading message while retrieving results via AJAX, but I can't. Can anybody help please?
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "do_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#search_result_box").show();
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
I would change the message before firing the AJAX request. So, on click or on submit:
<script>
$('form').on('submit', function(e) {
e.preventDefault();
$('#response').html('<p>Loading…</p>');
$.post($(this).attr('action'), $(this).serialize(), function(response) {
// do something here with the response
$('#response').html('<p>Request successful.</p>');
});
});
</script>
Why not using beforeSend and success methods to show/hide a loading message
beforeSend: function(html) { // this happens before actual call
// DO SOMEHTING HERE TO SHOW YOUR LOADING MESSAGE AS $('#loading').show();
$("#results").html('');
$("#search_result_box").show();
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
// DO SOMEHTING HERE TO HIDE YOUR LOADING MESSAGE AS $('#loading').hide();
$("#results").show();
$("#results").append(html);
}
rgds

Categories