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.
3
Answers
As an option you can create an object where you store your urls and then select required url by key:
Another option: you can define urls in
form
‘saction
attribute:In your script:
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.
Note you need to specify url in form action
Server side in php part,
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 –
Each form has unique id attribute and a common class for button.
@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.