Cannot get Ajax update form to work with unserialize - php

I'm trying to put together a working demo (including mysql) of a form that uses jquery to serialize form data and php to retrieve the data so that it can be passed to a mysql query.
The form seems to be posting data correctly but I'm not sure how to set up the processing script which sees $_POST to unserialize the data so that I can pass it to mysql. You can see the demo at http://www.dottedi.biz/demo/code/ajax/serialize .
I have tried using:
$data=unserialize($_POST['data']);
to unserialize the data but it comes back empty. A simple print_r ($_POST); returns the array data from the form. You can see that if you test the demo. Suggestions please?
Added info - the contents of the script.js file:
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
var input = $(this);
var value = input.val();
var column = input.attr('name');
var form = input.parents('form');
var linked_col = form.find('#associated').attr('name');
var linked_val = form.find('#associated').val();
// var serializedData = $(this).serialize();
$("#Status").html( "" );
$.ajax({
url: "update.php",
data: {
val: value,
col: column,
id: linked_col,
id_val: linked_val
},
type: "POST",
success: function(html) {
$("#Status").html( html );
}
});
});
});
});
9/22 - shortened script.js
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
$("#Result").html( "" );
$.ajax({
url: "update.php",
data: $('form').serialize(), // works to post data
type: "POST",
success: function(html) {
$("#Result").html( html );
}
});
});
});
});
Comment - I tested and it seems that the same data is posted using serialize as above vs creating a variable like var serializedData = $(this).serialize() and posting the variable, but this is shorter.

Perhaps you should
$('form').submit(function(evt) {
// Serialize the data in the form
var serializedData = $(this).serialize();
//send off serializedData in your ajax
}
THEN
php script will have
$data=json_decode($_POST['data']);
NEW WAY
$.ajax({
url: "update.php",
data: {'data': $('form').serialize()}, // works to post data
type: "POST",
success: function(html) {
$("#Result").html( html );
}

Related

Getting form field value separately in AJAX while using the "serialize" method

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

How do I prevent a PHP/Ajax script using serialize from multiple submits?

I am using PHP/Ajax/serialize to submit a simple form to itself. I use the following JavaScript to set it up to serialize/post the data. You can see the demo at https://www.dottedi.biz/demo/code/public/addtocart.php. There is a link to a .txt version of the script.
$(function() {
var form = $("#addtocart");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$("#result").html( "" );
$.ajax({
type: "POST",
url: $(form).attr("action"),
data: formData,
success: function(html) { $("#result").html(html); }
})
});
});
Upon clicking the Buy it now button, it should only add a single line to the database. The first time you click on the button it adds a single line. If you click again, it adds two new lines, then three new lines, etc. It is sequentially adding more lines if you click submit. To stop this, you must reload the form.
Place the id of the button in id = "addtocart_id"
$(function() {
var form = $("#addtocart");
var count_btn = true;
form.submit(function(e) {
e.preventDefault();
if(count_btn){
var formData = form.serialize();
$("#result").html("");
$.ajax({
type: "POST",
url: form.attr("action"),
data: formData,
beforeSend: function () {
$("#addtocart_id").html("Please Wait...").prop("disabled", true);
},
success: function(html) { $("#result").html(html); }
complete: function(){
count_btn = false;
$("#addtocart_id").html("Now Reload from browser");
}
})
}
});
});

How to post form serialize data using PHP?

I have a form that contain dynamically generated fields. I need to post the form using .serialize().
Ajax
$("#save").click(function () {
formData = $('#myForm').serialize();
$.ajax({
type:"POST",
url: base_url +'home/save',
data: {
formData:formData,
csrf_test_name: csrf_token
},
success: function(response){
console.log(response);
alert(response);
}
});
});
I need to post all the data using input field name. Now I got all the result like that:
echo $fomdata=$this->input->post('formData');
output
room_count_new=5&room_id=1&bedcount_1_1=1&extra_age_1_1_1=middle&extra_age_1_1_2=0&bedcount_1_2=0
But I want to post with the corresponding name.
Get rid of the object with formdata property and only send the serialized string and add the csrf to the end of it or add the csrf to the form as a hidden input and let it get serialized also in serialize()
$("#save").click(function() {
var formData = $('#myForm').serialize();
formData += '&csrf_test_name=' + csrf_token
$.ajax({
type: "POST",
url: base_url + 'home/save',
data: formData,
success: function(response) {
console.log(response);
alert(response)
}
});
});
Then in php access the same names as in form.
$fomdata=$this->input->post();
$roomCount = $fomdata['room_count_new'];
$csrfToken = $fomdata['csrf_test_name'];

How to utilize the Ajax call success return data to php code for running mysql query in same file

I am getting data from ajax call. But that data is coming in Jquery and I have saved it in a variable. Now I want that data to be utilized for running some php and mysql code. Can any one solve this?
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result);
//$('.alert').show().html(result).delay(2000).fadeOut(3000);
setTimeout(function(){window.location.href = "index.php";},2000);
}
});
}
return result;
});
If what you want is to navigate to the index.php page on click of that button, then, do it this way:
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result) {
alert(result); //you may remove this. use console.log for debugging your js next time
setTimeout(function(){window.location.href = "index.php?result="+result;},2000); //why the timeout?
}
});
}
});
The easier and proper solution should be to re-use ajax to use this variable in another PHP file.
$("#submit_bt").click(function () {
var name = $('#search-box').val();
var dataString = 'name=' + name;
if (name == "" ){
$('.alert').show().html('Please fill all information')
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "read_data.php",
data: dataString,
cache: false,
success: function (result)
{
//AJAX code to execute your MySQL query
$.ajax({
type: "POST",
url: "read_data2.php",
data: result,
cache: false,
success: function (result)
{
//Manage your read_data2.php output
}
});
}
});
}

Data not passing through AJAX

I am trying to pass a value of a button using some ajax to a separate file.
Here is my code.
$("input#downloadSingle").click(function() {
var myData = $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
However, when I test out the next page by doing a var_dump on $_POST. I don't get any data back. Thoughts?
You're not specifying the name of the $_POST variable you're gonna get on the singleDownload.php file (unless that's part of the button's value), so you should try something like:
$("input#downloadSingle").click(function() {
var myData = "whatever=" + $("input#downloadSingle").val();
$.ajax({
type: 'post',
url:'singleDownload.php',
data: myData,
success: function(results) {
alert('works');
}
});
});
And make sure $_POST in your php file is the same whatever variable

Categories