Ajax form post with form element name as array - php

I have a form with element names as multi-dimensional array like
<form method="post" id="formDealOptions" name="formDealOptions">
<table>
<tr class="dealOptionRow saved">
<td>
<input type="text" name="dealOptionsGroup[1][dealOptionName]" value="dealOptionName1">
</td>
<td>
<input type="text" name="dealOptionsGroup[2][dealOptionName]" value="dealOptionName2">
</td>
</tr>
</table>
</form>
If i post this form using normal form submit, $_POST array is like
Array(
'dealOptionsGroup' => Array( '1' => Array('dealOptionName' => dealOptionName1 )
'2' => Array('dealOptionName' => dealOptionName1 )
)
)
This is fine and i have created server side validation using this array structure. But when is submmit the same form through ajax call using serializeArray() like
var data = new Object();
data.postValues = $('#formDealOptions').serializeArray();
$.ajax({
type: "POST",
url: GLOBAL_BASE_PATH + '/deal/ajaxsaveDealOptions/',
data: data,
success: function (data) {//}
});
Now the post array is like
[postValues] => Array
(
[0] => Array
(
[name] => dealOptionsGroup[1][dealOptionName]
[value] => dealOptionName1
)
[1] => Array
(
[name] => dealOptionsGroup[2][dealOptionName]
[value] => dealOptionName2
)
)
Is there any way to post array using ajax as same in normal form post.

<form method="post" id="formDealOptions" name="formDealOptions">
<table>
<tr class="dealOptionRow saved">
<td>
<input type="text" name="dealOptionsGroup[1][dealOptionName]" id="aa" value="OptionName1">
</td>
<td>
<input type="text" name="dealOptionsGroup[2][dealOptionName]" value="OptionName2">
</td>
<td>
<input type="submit" name="forms" id="" value="save">
<input type="button" name="forms" id="submitButtonId" value="save">
</td>
</tr>
</table>
</form> <script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var frm = $('#formDealOptions');
frm.submit(function () {
$.ajax({
type: 'post',
url: 'test.php',
data: frm.serializeArray(),
success: function (data) {
alert(data);
}
});
return false;
});
</script>
test.php
---------
<?php
print_r($_REQUEST);
?>

You can use form like this.Then post the values.
<form method="post" id="formDealOptions" name="formDealOptions">
<table>
<tr class="dealOptionRow saved">
<td>
<input type="text" name="dealOptionsGroup[dealOptionName][]" value="dealOptionName1">
</td>
<td>
<input type="text" name="dealOptionsGroup[dealOptionName][]" value="dealOptionName2">
</td>
</tr>
</table>
</form>

Dont serialize
$.ajax({
type: "POST",
url: GLOBAL_BASE_PATH + '/deal/ajaxsaveDealOptions/',
data:{
'data1':$('input[value="dealOptionName1"]').val(),
'data2':$('input[value="dealOptionName2"]').val(),
//.....
},
success: function (data) { }
});
And in php
<?php $_POST['data1']; //etc ?>

Related

Can't Send while looped input field data from ajax to php

I have two input fields with same class name and the same data.
Here is my while loop generated input field
<tr>
<td>
<input onchange="mySubmit(this.form)" class="ot_value" name="ot_value" type="text" value="10">
<input type="hidden" name="ot_id" class="ot_id" value="1">
</td>
</tr>
<tr>
<td>
<input onchange="mySubmit(this.form)" class="ot_value" name="ot_value" type="text" value="11">
<input type="hidden" name="ot_id" class="ot_id" value="2">
</td>
</tr>
I was trying to send data from ajax to php when user change any value.
Here is my jquery
function mySubmit(theForm) {
var ot_value= $(".ot_value").val();
var ot_id= $(".ot_id").val();
$.ajax({
type:"post",
url:"../apis/update_ot.php",
data: "ot_value=" + ot_value+ "&ot_id=" + ot_id,
success:function(data){
alert(data);
}
});
}
I was able to send data when user is changing any input field data. But the problem is that, it's taking only the 1st row data.
How can I get the exact data, that what user are changing in input field.
You have jQuery, use it
remove onchange="mySubmit(this.form)" from the field and do
$(function() {
$(".ot_value").on("change", function() {
const ot_value = $(this).val();
const ot_id = $(this).next(".ot_id").val();
console.log("about to submit",ot_value,ot_id)
$.ajax({
type: "post",
url: "../apis/update_ot.php",
data: "ot_value=" + ot_value + "&ot_id=" + ot_id,
success: function(data) {
alert(data);
}
});
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
<input class="ot_value" name="ot_value" type="text" value="10">
<input type="hidden" name="ot_id" class="ot_id" value="1">
</td>
</tr>
<tr>
<td>
<input class="ot_value" name="ot_value" type="text" value="11">
<input type="hidden" name="ot_id" class="ot_id" value="2">
</td>
</tr>
</tbody>
</table>

How can I send an array to Codeigniter with jQuery AJAX

I have an array of marks of students :
<span>Teacher Name : </span> <input id="teacher" type="text">
<span>Course Name : </span> <input id="course" type="text">
<table id="students_list">
<tr>
<td><span>George</span></td>
<td><input class="mark-field" type="text" id="1105"/></td>
</tr>
<tr>
<td><span>Danny</span></td>
<td><input class="mark-field" type="text" id="1351"/></td>
</tr>
<tr>
<td><span>Linda</span></td>
<td><input class="mark-field" type="text" id="3486"/></td>
</tr>
<tr>
<td><span>Mario</span></td>
<td><input class="mark-field" type="text" id="9032"/></td>
</tr>
…
</table>
<button id="save_marks">SAVE</button>
I use this method to create an array with JQUERY and send it to server :
$(document).on('click', '#save_marks', function () {
var dataArray = [];
var i = 1;
$('.mark-field').each(function () {
dataArray[i] = {
'teacher' : $('#teacher').val(),
'course' : $('#course').val(),
'mark' : $(this).val(),
'id' : $(this).attr('id')
};
i++;
});
dataArray[0] = i;
$.ajax({
url: 'save-marks',
data: {dataset: dataArray},
type: 'post',
success: function (res) {
alert(res);
}
});
});
and use this way to change it to PHP (CodeIgniter) array and save it on database :
public function save_marks() {
$arrayLength = $this->input->post('data')[0];
for ($i = 1; $i < $arrayLength; $i++) {
$arr[] = array(
'TEACHERS' => $this->input->post('dataset')[$i]['teacher'],
'COURSES' => $this->input->post('dataset')[$i]['course'],
'MARKS' => $this->input->post('dataset')[$i]['mark'],
'ID' => $this->input->post('dataset')[$i]['id']
);
}
$this->db->insert_batch('marks_table', $arr);
die($this->db->affected_rows() . ' marks were saved.');
}
Now my questions :
Is there another way to calculate array length on the server side?
Is it a good way to build an array both on the server side and on the client side?
and if no
Is there another way to create and send them to the server?
Thanks.
1. Is there another way to calculate array length on the server side?
Yes, by using sizeof($array), you can get the array length of the array.
2. Is it a good way to build an array both on the server side and on the client side?
Using name="mark-field[]" you can send the mark list without manually construct it in your javascript, also by using sizeof($array) you can get array size in the server side without sending the size from your javascript.
3. Is there another way to create and send them to the server?
Personally, I would do something like this:
<form id = "form_data" method="post">
<span>Teacher Name : </span> <input id="teacher" name="teacher" type="text">
<span>Course Name : </span> <input id="course" name="course" type="text">
<table id="students_list">
<tr>
<td><span>George</span></td>
<td>
<input name="mark[]" type="text" id="1105"/>
<input name="mark_id[]" type="hidden" value="1105"/>
</td>
</tr>
<tr>
<td><span>Danny</span></td>
<td>
<input name="mark[]" type="text" id="1351"/>
<input name="mark_id[]" type="hidden" value="1351"/>
</td>
</tr>
<tr>
<td><span>Linda</span></td>
<td>
<input name="mark[]" type="text" id="3486"/>
<input name="mark_id[]" type="hidden" value="3486"/>
</td>
</tr>
</table>
<button id="save_marks">SAVE</button>
</form>
and the javascript part
$(document).on('submit', '#form_data', function (event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
//fill url with your controller name
url:"<?php echo base_url(); ?>controllername/save_marks",
method:"POST",
data: data,
async: false,
processData: false,
contentType: false,
cache:false,
dataType:"json",
success:function(returndata)
{
//do something with your returned data
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
});
and in your controller:
public function save_marks() {
$teacher= $this->input->post('teacher',true);
$course= $this->input->post('course',true);
//mark & mark_id is an array
$mark= $this->input->post('mark',true);
$mark_id= $this->input->post('mark_id',true);
$arr = array();
foreach($mark_id as $key => $row)
{
$arr[] = array(
'TEACHERS' => $teacher,
'COURSES' => $course,
'MARKS' => $mark[$key],
'ID' => $row
);
}
$this->db->insert_batch('marks_table', $arr);
//die($this->db->affected_rows() . ' marks were saved.');
echo json_encode($arr);
}
By sending formdata, you wont need to manually construct the array, however since you need to send the mark_id to the controller, you need to add 1 more field to send the mark_id

Cannot able to fetch data from ajax to php page

I design a simple page were user can put name, password and image using html.
I try to sent those data using ajax to specific php page, but I cannot implement this.
how I do this thing
Html code
<?php include('connection.php'); ?>
<form id="form" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input type="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="pass"></td>
</tr>
<tr>
<td>Photos:</td>
<td><input type="file" id="photos"></td>
</tr>
<tr>
<td><input type="submit" id="go"></td>
</tr>
</table>
</form>
Jquery and ajax
<script>
$(document).ready(function(){
$('#go').click(function(){
var img_name = $('#img_name').val();
var name = $('#name').val();
var pass = $('#pass').val();
$.ajax({
type : "POST",
url : "singup_submit.php",
data : { img_name:img_name, name:name, pass:pass},
success : function(done){
alert(done);
}
});
});
});
</script>
Php code
<?php
include('connection.php');
if(isset($_POST)){
$name = $_POST['name'];
$pass = $_POST['pass'];
$img_name=$_FILES['img_name']['name'];
$qr="INSERT INTO data (name,pass,img_name) VALUES ('$name','$pass','$img_name')";
$ex=mysqli_query($con,$qr) or die(mysqli_error($con));
if($ex==1)
echo 'done';
else
echo 'not done';
}
Follow this code ..It may help you
<script>
$(document).ready(function(){
$("#go").click(function(){
var name = $("#name").val();
var pasword = $("#password").val();
var photos = $("#photos").val();
if(name==''||pass==''||photos==''){
alert("Please Fill All Fields");
}
else{
$.ajax({
type : "POST",
url : "singup_submit.php",
data : formData,
cache : false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
</script>
you are not sending any file in your ajax request.
$(document).ready(function(){
$("#go").on('submit',function(e){
e.preventDefault()
$.ajax({
url: 'singup_submit.php',
type: 'POST',
data: new FormData(this),
contentType: false,
processData: false,
success: function(response){
alert(done);
},
error: function(data){
console.log("error");
console.log(data);
}
},
});
});
});
and then take data from global variables in php as you are doing now.
and please assign name to your form fields like so
<form id="form" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input type="name" name="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" id="pass"></td>
</tr>
<tr>
<td>Photos:</td>
<td><input type="file" name="img" id="photos"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="go"></td>
</tr>
</table>
</form>
and it should work.

don't get POST variables after submit Multipart/form-data

A part on my page is responsible for multiple picture uploads, it worked for a while but it is not working anymore.
I'm using a WampServer Version 3.1.7 64bit and testing on localhost.
I have tried accepting and sending datas via ajax instead of html submit, but i didn't get datas on php side either, but on client side i had all datas before sending ( FormData() ).
HTML part:
<div class="div_shadow_here">
<form id="gallery_data" method="post" enctype="multipart/form-data">
<input type="hidden" name="formid" value="<?php echo $_SESSION[" formid "]; ?>" />
<table class="news_table">
<tr>
<td>
<p class="name_col">Gallery name:</p>
</td>
<td>
<input class="input_news" id="gallery_title" type="text" name="gallery_title" />
</td>
</tr>
<tr>
<td>
<p class="name_col">Picture(s):</p>
</td>
<td>
<input class="input_news" id="news_picture_path" type="file" name="picture_path[]" multiple />
<label id="label_for_input" for="picture_path">Select picture(s)</label><span id="uploadState"></span>
</td>
</tr>
<tr>
<td></td>
<td>
<div id="img_container"></div>
</td>
</tr>
</table>
<button class="print_button hidden_a" type="submit" name="login" id="save_news" form="gallery_data">Save</button>
</form>
</div>
PHP part for testing:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<script>console.log("Not empty")</script>';
if (isset($_POST['formid'])) {
echo '<script>console.log("'.$_POST['formid'].
'")</script>';
}
if (isset($_POST['gallery_title'])) {
echo '<script>console.log("'.$_POST['gallery_title'].
'")</script>';
}
if (isset($_FILES['picture_path']['name'])) {
echo '<script>console.log("'.count($_FILES['picture_path']['name']).
'")</script>';
}
} else {
echo '<script>console.log("Empty")</script>';
}
I get Notice: Undefined index: gallery_title.. errors without isset($_POST['gallery_title']) testing (same for all other input fields).
Ajax for testing:
$('body').on('click', '#save_news', function(e) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
for (var key of formData.keys()) {
console.log(key);
}
for (var value of formData.values()) {
console.log(value);
}
$.ajax({
url: 'galleryupload.php',
type: 'POST',
success: function(data) {
alert("Data Uploaded: " + data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});

multiple select with checkbox in php

i am making a website in which i am to embbed the functionality of delete using multiple checkbox. here is my code. my problem is
1. Ajax call is not working.
2. how can i make search from database for array .
<?php
if(isset($_POST['Delete']))
{
$array=$_POST['check_box'];
}
?>
<form method="post" id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while($selectnumberarr=mysql_fetch_array($selectnumber))
{
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" id="<?php $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}?>
<input type="submit" name="Delete" id="delete">
</table>
</form>
and below is my ajax and javascript code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
any help would be appriciated
your code is almost correct. You need to remove `onChange="show()" for input checkbox, because if you have jquery then you don't need to put events on HTML elements.
Use jquery 'on' method for compatibility for latest php library.
Replace your jquery code with following jquery code :-
<script>
$(document).ready(function(){
$('#delete').on('click',function()
{
var cat_id = $('.check_box:checked').map(function() {
return this.id;
}).get().join(',');
console.log(cat_id);
$.ajax({
type: "POST",
url: "checkbox.php",
data: { "kw ":cat_id },
datatype:'json',
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
Use ".check_box" instead of "element" in jquery to prevent checks for all checkboxes, instead of desired ones.
Hope it helps.
Why you don't use an array for sending the checkboxes like:
HTML part:
<?php
if (isset($_POST['check_box'])) {
var_dump($_POST['check_box']);
echo "ajax call is working";
}
?>
<form id="form">
<table width="200" border="1">
<tr>
<td>select</td>
<td>NAme</td>
<td>Action</td>
</tr>
<?php
while ($selectnumberarr = mysql_fetch_array($selectnumber)) {
?>
<tr>
<td><input type="checkbox" name="check_box[]" class="check_box" value="<?php echo $selectnumberarr[0]; ?>" /> </td>
<td><?php echo $selectnumberarr[1]; ?></td>
</tr>
<?php
}
?>
</table>
<input type="button"name="delete" id="delete" value="Delete" />
</form>
JQuery part:
<script type="text/javascript">
$(document).ready(function(){
$('#delete').click(function() {
$.ajax({
type: "POST",
url: "checkbox.php",
data: $('#form').serialize(),
cache: false,
success: function(html)
{
alert("true");
}
});//end ajax
});
});
</script>
So you can easily get an array of the selected checkboxes in php with:
$idsArray = $_POST["check_box"];
this looks now like:
array(
"1", "2","etc.."
);
so this array contains all the ids of the selected checkboxes for delete.

Categories