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'];
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);
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 );
}
$("#submit_login").click(function(){
var username=$('input[name=user_email]');
var password=$('input[name=user_password]');
var data;
data: "name="+username+"&pwd="+password,
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: data,
success: function(data) {
alert("Form submitted successfully");
}
});
});
How to give the data variable so that we can fetch it in PHP using $_REQUEST?
The above representation of the data variable shows an error.
You can pass the data as json,
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: {
name: username,
pwd: password
},
success: function(data) {
alert("Form submitted successfully");
}
});
Also, names should match the parameters in the function.
Client Side
$("#submit_login").click(function(){
var username=$("input[name='user_email']").val();
var password=$("input[name='user_password']").val();
$.ajax({
type: "POST",
dataType: "json",
url: "newExam.php",
data: {name : username, pwd : password },
success: function(data) {
alert("Form submitted successfully");
}
});
});
Server Side
<?php
// file : newExam.php
// to view post array
if(!empty($_POST))
{
print_r($_POST);
}
// access individual element
if(isset($_POST['name']))
{
echo $_POST['name'];
}
?>
The above representation of the data variable shows an error.
Absolutely. That is correct because there is an error. You have a variable and you are assigning a query string with : where it should be =:
data= "name="+username+"&pwd="+password;
But this is not a good idea because you have to post the values not the input objects. username is an html input element, instead you should post an object like:
$("#submit_login").click(function(){
var username=$('input[name=user_email]').val();
var password=$('input[name=user_password]').val();
var data = {name:username, pwd:password};
$.ajax({
type: "POST",
dataType: "json", // <---make sure you return json from the php side.
url: "newExam.php",
data: data,
success: function(data) {
alert("Form submitted successfully");
}
});
});
Your selectors dont look right to me.
var username=$('input[name="user_email"]');
var password=$('input[name="user_password"]');
Note the double quotes around the input name attributes
Can you try the below code format:
data: {name : username, pwd : password }
This is the jquery ajax part in which i have sent json data to the php file.
$(function () {
$('form').submit(function () {
var fields = $(this).serializeArray();
var ans_json = JSON.stringify(fields);
console.log(ans_json);
$.ajax({
url: "results.php",
type: "POST",
data: ans_json,
dataType: "json",
success: function (result) {
console.log(result);
}
});
return false;
});
});
Now i want to use this json data sent to the php page.How can i do it? I have done it this way but it returns null.
<?php
echo json_decode('ans_json');
?>
I have a set of 10 questions which need to be answered. 3 questions were answered so got the below result.This is what i got in my console.
[{"name":"answer_9","value":"a"},{"name":"answer_10","value":"a"}] quizzes.php:14
null
You don't need to decode any JSON string at server-side if you encode properly your parameters.
You can use .serialize() to do the form serialization for you, and it's ready to send.
$(function () {
$('form').submit(function () {
var serialized = $(this).serialize();
$.ajax({
url: "results.php",
type: "POST",
data: serialized,
...
});
return false;
});
});
Your parameters will be available in your $_POST as in any normal POST request. For example,
$ninth_answer = $_POST["answer_9"];
You need to decode the POST variable. Currently you're decoding just a string which even isn't valid JSON.
<?php
$json_arr = json_decode($_POST['my_json'], true);
var_dump($json_arr);
echo "First name in json is:". $json_arr[0]['name'];
?>
and edit your javascript to reflect following:
This posts my_json parameter with your json as an value. This makes it easy for PHP to recieve it using $_POST.
$.ajax({
url: "results.php",
type: "POST",
data: {"my_json": ans_json},
dataType: "json",
success: function (result) {
console.log(result);
}
});
I suggest to read a little about those things:
http://api.jquery.com/jQuery.ajax/
http://ee1.php.net/manual/en/function.json-decode.php
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