I have a form which I'm validating using jQuery and php. So basically if the php echoes "input must be filled" the jQuery should put a red border around that input, but the thing works only after submitting the form two times.
I explain: if I submit with input unfilled the php file echoes "input must be filled", but only if I press again the submit button - the input goes red.
$("form#maj_email").submit(function(){
var _data = $(this).serialize()
$.ajax({
type: 'POST',
url: 'validation_profil.php?var=maj_email',
beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localhost/www3/images/ajax_loader.gif')"})
$("div#error_maj_email").hide()
if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
$("form#maj_email input:[name=email]").css({border:"1px solid red"})
}
},
data:_data,
cache: false,
success: function(html){
$('div#error_maj_email').html(html)
$("div#ajax_icon_maj_email").css({background:"url('none')"})
$("div#error_maj_email").fadeIn()
}
})
})
It looks like the form is being submitted via the form instead of your ajax call. You need to prevent this behavior for this to work:
$("form#maj_email").submit(function(e){
var _data= $(this).serialize();
$.ajax({
type: 'POST',
url: 'validation_profil.php?var=maj_email',
beforeSend: function(){
$("div#ajax_icon_maj_email").css({background:"url('http://localhost/www3/images/ajax_loader.gif')"})
$("div#error_maj_email").hide()
if( $("div#error_maj_email").text()=="Email syntaxe incorrecte"){
$("form#maj_email input:[name=email]").css({border:"1px solid red"})
}
},
data:_data,
cache: false,
success: function(html){
$('div#error_maj_email').html(html)
$("div#ajax_icon_maj_email").css({background:"url('none')"})
$("div#error_maj_email").fadeIn()
}
});
e.preventDefault();
return false;
})
Related
I am using AJAX to process my form data. I have to write multiple functions for multiple form. But I was thinking if I could use a single ajax function for multiple forms from different pages. For example, currently I am using it like this:
// Update Password
$('#updPass').click(function() {
var form = document.updPass;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: 'processes/settings.php',
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$("#updPass").val('Please wait...');
},
success: function(html){
$("#updPass").val('Save');
$('.message').html(html).fadeIn();
}
});
return false;
});
// Add New Room
$('#addRoom').click(function() {
var form = document.addRoom;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: 'processes/rooms.php',
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$("#addRoom").val('Please wait...');
},
success: function(html){
$("#addRoom").val('Save');
$('.message').html(html).fadeIn();
}
});
return false;
});
But I want to use it like this:
// Perform action
$('#addNew').click(function() {
var form = document.addNew;
var dataString = $(form).serialize();
var formFieldToIdentify = "Take input from 1 hidden form field and store here";
$.ajax({
type: 'POST',
if(formFieldToIdentify == 'password'){
url: 'processes/settings.php',
}else{
url: 'processes/rooms.php',
}
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$("#addNew").val('Please wait...');
},
success: function(html){
$("#addNew").val('Save');
$('.message').html(html).fadeIn();
}
});
return false;
});
How to obtain that formFieldToIdentify variable from the form here? If I am able to get it I can use it easily. If I collected the form values separately the job would have been done. But here, I am using the serialize method and hence unable to separately get this form field value.
As an option you can create an object where you store your urls and then select required url by key:
var urls = {
addNew: 'processes/rooms.php',
someUrl: 'processes/file1.php',
//...
};
$('#addNew').click(function() {
var form = document.addNew;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: urls.addNew,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$("#addNew").val('Please wait...');
},
success: function(html){
$("#addNew").val('Save');
$('.message').html(html).fadeIn();
}
});
return false;
});
Another option: you can define urls in form's action attribute:
<form action="/file.php" method="POST">
In your script:
$('#addNew').click(function() {
var form = document.addNew;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr("action"),
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$("#addNew").val('Please wait...');
},
success: function(html){
$("#addNew").val('Save');
$('.message').html(html).fadeIn();
}
});
return false;
});
So you told me that you didn't get my idea that I was told you.
So this is the brief answer of my idea.
Suppose you have three forms in different pages or in a same page like this -
<form id='registration_form'>
form fields like input, radio buttons, checkboxes, textareas etc
<input type='submit' class='form_btn'>
</form>
//***************************
<form id='login_form'>
form fields like input, radio buttons, checkboxes, textareas etc
<input type='submit' class='form_btn'>
</form>
//***************************
<form id='update_form'>
add form fields like input, radio buttons, checkboxes, textareas etc
<input type='submit' class='form_btn'>
</form>
//****************************
Each form has unique id attribute and a common class for button.
<script>
// create variables
let process_url, method, form, dataString;
// for submit button.
let form_btn = document.getElementsByClassName('form_btn');
// AJAX code to process the form data.
function your_ajax_function(){
$.ajax({
type: method,
url: process_url,
data: dataString,
cache: true,
beforeSend: function(){
// fetch those ID's and classes in function set_dynamic_variables()
// and then use here.
},
success: function(html){
// fetch those ID's and classes in function set_dynamic_variables()
// and then use here.
}
});
}
function set_dynamic_variables(e){
form = //write your own code to fetch the form-ID in which e is present.
switch (form) {
case 'registration_form':
process_url = './process/registration_form.process.php';
method = 'POST';
dataString = $('#' + form).serialize();
break;
case 'login_form':
process_url = './process/login_form.process.php';
method = 'POST';
dataString = $('#' + form).serialize();
break;
case 'update_form':
process_url = './process/update_form.process.php';
method = 'POST';
dataString = $('#' + form).serialize();
break;
default:
// statements_def
break;
} // switch()
} // if
// adding the event-listener for all the submit button of forms
for(let i=0; i< submit_btn.length; i++){
submit_btn[i].addEventListener('click', function(e) {
e.preventDefault();
set_dynamic_variables(e);
your_ajax_function();
}, false);
</script>
#Golden Friendship Site So, This is what I told you in discussion.
and my code will be able to work correctly even if you put all form in a same page.
Previus answer is good too, I just wanted to clear that you cant send data to multiple urls with one function.
For sending data to multiple pages you need to created nested functions in ajax, which will start all functions with same button clicked.
But you can get values from multiple forms in same page or in different pages without changing function each time like following example.
$('#updPass').click(function(e){
e.preventDefault();
var url = $(this).attr('action'); //auto detect action url
var results = [];
$('form').each(function(){
results.push($(this).serialize());
// serializeArray(); is much more suitable
//results.push($(this).serializeArray());
});
$.ajax({
'url': url,
'type': 'POST', // type not method
'data': {data: JSON.stringify(results)},
'dataType': 'html',
'success': function (data) {
console.log(data);
}
});
});
Note you need to specify url in form action
Server side in php part,
var_dump(json_decode($_POST));
var_dump($_POST);
In product-master.php (view page), I have a few buttons: Add, Edit, Delete.
Each button got unique name: btnAddProduct, btnEditProduct, btnDelProduct
These buttons share the same action page as shown in the ajax code below: action/product-master.php (yes I named it according to the view page, just different folder)
Yes, I'm using ajax method to process form data. How to validate which button was pressed?
I tried using isset($_POST['btnAddProduct']) but it is not working. Below is my button:
btnAddProduct
<input type="submit" class="btn btn-success" id="btnAddProduct" name="btnAddProduct">
product-master.php
$('#btnAddProduct').on('click', function(e) {
var formData = new FormData($('#form-add-modal')[0]);
$.ajax({
url: "action/<?php echo basename(__FILE__); ?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(){
//Display error here
}
});
});
Buttons aren't included when you create a FormData from a form, since the FormData constructor has no way of knowing which button was clicked. You need to add it to the FormData explicitly.
$('#btnAddProduct').on('click', function(e) {
var formData = new FormData($('#form-add-modal')[0]);
formData.set(this.name, "1");
$.ajax({
url: "action/<?php echo basename(__FILE__); ?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(){
//Display error here
}
});
});
I am trying to create a simple shopping cart using AJAX and PHP.
Everything works as it should BUT 1 thing doesn't work all the time and it seems that it fails to execute. (it works 3 times out of 5).
to explain this issue please take a look at the code bellow:
jQuery(document).ready(function() {
//////////////////////LETS RUN OUR ADD TO CART FEATURE USING AJAX //////////////
$(function(){
$('.form1').on('submit', function(e){
$( "#preloader" ).fadeIn( 850 );
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: $(this).attr('action'),
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$( "#preloader" ).fadeOut( 850 );
}
});
});
});
//////////////////////LETS RUN LOAD THE cart-header.php ON PAGE LOAD USING AJAX //////////////
$(document).ready(function () {
function load1() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data2) {
$('#headerCart').html($(data2));
//setTimeout(load2, 500);
}
});
}
load1();
});
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS RUN OUR DELETE FROM CART FEATURE USING AJAX //////////////
$(document).on('submit', '.delForm', function(dleItem){
// prevent native form submission here
dleItem.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS GET THE QUANTITY OF CURRENT ITEMS ADDED IN THE CART USING AJAX/////////////
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart.php",
//url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data) {
$('.item_count').html($(data).find('#total').text());
//$('#headerCart').html($(data));
setTimeout(load, 1000);
}
});
}
load();
});
I have commented the code so you can see the parts of the code and what they do.
the issue is this part:
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
As I mentioned above, this code works fine but it only works when it wants to as if it has mind of its own!
could someone please advise on this issue?
Thanks in advance.
I'm using jQuery and PHP to post a long dynamically created HTML Form. Since I need to have a "Sending" dialog and show the results on the same page (ideally in a jQuery popup), I do not use the traditional HTML form submit. What I'm doing works great except that File input types do not upload.
Is there a way to do this?
Here is my code:
jQuery:
function submitForm(submiturl)
{
$.blockUI({ message: "<h2>Submitting...</h2>" });
var form = $('#theForm').serialize();
var fields = "<?= urlencode(serialize($allFields)) ?>";
$.ajax({
url: submiturl,
data: {form: form, fields: fields, extraResults: window.extraResults},
type: "post",
cache: false,
complete: function() {
// unblock when remote call returns
$.unblockUI();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR");
},
success: function( strData ){
alert("SUCCESS: " + strData);
}
});
}
mention enctype="multipart/formdata" in the form and use this code in your function
var uf = //get form id;
var fd = new FormData(uf);
$.ajax({
type: "POST",
url: "xxxxx.php",
data: fd,
processData:false,
contentType: false,
success: function(msg){ }
});
I am trying to create a post using Ajax and jQuery.
But it isn't working. It just refreshes the current page.
HTML :
<form name="update_text_post" action="" id="update_text_post" method="post">
<textarea name="textbox" class="textbox" maxlength="600"></textarea>
<input type="submit" name="submit" value="Update" class="update_post_submit">
</form>
jQuery :
$('#update_text_post').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
return false
});
The e.preventDefault(); is not working aswell.. it actually is not even performing the MYSQL query . Seems like it is not even sending the form or targeting the post_ajax2.php file.
You need to use .preventDefault() to stop the default form submit behavior with page reload.
$(function() {
$('#update_text_post').submit(function(e) {
e.preventDefault(); // e.preventDefault() for prevent form submisson with page reload
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
// 1. you missed $ here, so it will not be a dom ready callback.
// your case is just define a function, and without executing it.
$(function () {
$('#update_text_post').submit(function (e) {
// 2. you need to prevent the default submit event.
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
You have to stop the default behavior of the submit button (form posting).Otherwise the form will be submitted again and you will see the page loading again ( you won't notice the change ajax brought to your page- some partial page updates ). You can use the preventDefault function to do this.
$(function(){
$('#update_text_post').submit(function(e) {
e.preventDefault(); // prevent the default submit behaviour
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
Add return false.
$('#update_text_post').submit(function(e) {
$.ajax({
...
})
return false;
});
Clicking on a submit button does just that - it submits the form. If you want to replace the form submission with an AJAX POST request, you'll need to stop the form from also being submitted (and the page therefore reloading), by preventing the default behaviour of that event.
You can do this by calling return false; at the end of the callback function bound to the submit event handler, or by passing a reference to the event to the callback function and calling e.preventDefault() (where e refers to the event).
The key difference between the two methods is that return false, in a jQuery callback function, will also prevent the event from bubbling. In this case, that's not really a big deal.
You have to call e.preventDefault(); in your function to prevent the form submit.
$('#update_text_post').submit(function(e) {
// prevent form submit
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});