jQuery Dynamic form submission and Ajax call - php

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() {
........
.......
});

Related

Successive AJAX calls add an extra consecutive call

I have a pretty standard ajax call for a live update, however, say I call the the ajax, everything is good, but say I want to call it again, this time, I will get 2 calls, and if I try again then I'll have 3, I can verify this by invoking and alert and with the Network DevCon of Chrome, any idea why this is happening?
P.S: I'm using Laravel 5.1
$('button[name=act]').click(function() {
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function() {
icon.show();
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
$(icon).fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
});
The problem is that every time you click on the act button you call $("form").submit(), which adds anothersubmithandler to the form. So if you click on theact` button 3 times, and then click on the form's submit button, it will send 3 AJAX requests.
It's almost always wrong to bind one event handler inside another event handler, you should bind all the event handlers at top level.
var icon;
$(document).ajaxStart(function() {
if (icon) {
icon.show();
}
});
$('button[name=act]').click(function() {
icon = $(this).closest('div.thumbnail').find('i');
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
if (icon) {
icon.fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
The reason this is happening is because you are rebinding the submit event function every time the button is clicked which results in multiple copies of the function. Just move it out of the click even, and if you want to force a submit on a click, you can call the submit() function with no parameters to fire the event.
Try the following:
$(function(){
$('button[name=act]').click(function(){
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function()
{
icon.show();
});
$("form").submit(); //This submits the form on click
});
//This binds the function, so it should only be called once.
$("form").submit(function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr)
{
//BLAH
}
});
});
});
I noticed two other things you might want to address. You want to somehow update the icon after it is loaded. You will need to have some other way to find the icon inside of the success function (possibly looking at the data that came back could yield some information that could be useful. Since it is json, it should be easy to update.)
Also, the way you currently have it will bind to all forms on the page. In the event that you have multiple forms on the page, you will probably want to change the selector to use an id.
Hope this helps!
Based in incremental calls and my guessings, I have to say that you're printing this code each time you make the (ajax) call, leading to bind your form element again in each call..
Am I right?
JO.

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

Running AJAX query to refresh div with php file

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.

Jquery ajax get request

I am new to jquery and php, I have two input fields, zip and city, the city shall output a value based from the zip that the user input. The jquery script shall call a URL: http://domain.com/city?zip.php="zip; so that zip.php will return an echo value that will output to the city input field.
I tried using ajax getXMLHTTP. some times it works but sometimes not
Please Refer to the following code snippet below:
<input type="text" id="zip_code" name="zip_code" />
<input type="text" id="city" name="city" />
<script type="text/javascript">
// Some Jquery code here for ajax get request to http://domain.com/city?zip.php
</script>
if you are using jquery the use $.ajax option instead of getXMLHTTP
function passzipvalue(zip)
$.ajax({
type: "GET",
url : 'http://domain.com/city.php='
data:"zip="+zip,
success: function(msg){
$("#formsData").html(msg);
}
});
}
something like this or
$.get('http://domain.com/city.php?zip='+zip,function (msg){
$('#formsData').html(msg);
});
if you want to populate it in some input fields use .val instead of .html
Use jQuery.get, documented here. In the success handler, use the data argument to populate the city input.
Sample:
$.get('http://domain.com/city.php?zip='+$('#IdOfZipInput').val(), function (data){
$('#IdOfCityInput').val(data);
});
Use jQuery AJAX. For example:
var zip = $('#zip').val();
$.get('http://domain.com/city.php?zip='+zip,function (data){
$('#city').val(data);
});
$.ajax({
url: 'http://domain.com/city.php?zip='+zip,
type: get,
success: function(data){
$("div").html(data);
}
});
use this data will be displayed
If its a constantly updating element then use jquery.post as ie caches the "get" results.
jQuery.post('call.php',{ action: "get"}, function (data) {
jQuery('#content').append(data);
});
FInd the tutorial here http://vavumi.com/?p=257
try to use the jquery ajax
$.ajax({
type: "POST",
url: 'sample/test.php',//your url
data: data,//data to be post
cache: false,
success: function(html) {
alert(html);//response from the server
}
});
$.ajax({
url: 'url',
beforeSend: function (xhr) {
//show loading
}
}).done(function (data, xhr) {
//hide loading
//success
}).fail(function (xhr) {
//hide loading
//error
});

jquery autocomplete doesn't work?

I want to make autocomlplete for remote data source, I get all data from database and return it as jSon, using console I see that all data has been returned, but the autocomplete doesn't work, also the alert in my code doesn't work, here's my code
$("#cellPhoneNo").autocomplete({
source: function(request, response) {
var param = {
"action": "getCellPhoneNos"
};
$.getJSON("controllers/Customer.controller.php", param, function(result) {
alert('here'); //doesn't alert
// cellPhoneSource=result;
});
},
select: function(event, ui) {
alert('response');
}
});
EDIT
I try to get the source using GET , I make like this
source:function(request,response){
var param= {"action":"getCellPhoneNos"};
$.ajax({
type: "GET",
url: "controllers/Customer.controller.php",
data: param,
success: function(result){
alert('success');
}
});
},
it alerts but autocomplete doesn't work, I try to put the values in a text file and make the file in the url , the autocomplete works!!
Any explanation?!
http://net.tutsplus.com/tutorials/javascript-ajax/how-to-use-the-jquery-ui-autocomplete-widget/
This is a tutorial on using the autocomplete plugin. The response variable in your callback is a function that you can call to add an array of items to the autocomplete list. Parse result and push each item onto an array, then call response(array); If result is already an array, you can call response(result);
I noticed that in the success function you do not return the result from the ajax query, could that be an issue?
source : function(request,response) {
var param= {"action":"getCellPhoneNos"};
var source = 'nothing came back from the server';
$.ajax({
type: "GET",
url: "controllers/Customer.controller.php",
data: param,
datatype: 'json'
success: function(result) {
if(result !== undefined) {
source = result;
}
alert(source);
return source;
}
});
},

Categories