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
Related
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;
});
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 6 years ago.
I am a new developer. I have created a plugin for data insert WP dashboard. I am trying to insert images in my database. I am trying to form submit with Ajax in WordPress. There is my code. When I use input type=text data submitted successfully, but when I use input type=file then data not submitted. I want all data inserted in my database and file saved in the upload folder.
<form id="ajax_form" method="" action="<?php echo $_SERVER['REQUEST_URI']; ?> " enctype="multipart/form-data">
<table class='wp-list-table widefat fixed'>
<tr>
<th class="ss-th-width">Code</th>
<td><input type="text" name="code" value="<?php echo $code; ?>" class="ss-field-width" /></td>
</tr>
<tr>
<th class="ss-th-width">School</th>
<td><input type="text" name="name" value="<?php echo $name; ?>" class="ss-field-width" /></td>
</tr>
<tr>
<th class="ss-th-width">Image</th>
<td><?php wp_nonce_field('ajax_file_nonce', 'security'); ?>
<input type="hidden" name="action" value="my_file_upload">
<label for="file_upload">It's a file upload...</label>
<input type="file" name="file_upload">
</td>
</tr>
</table>
<input type='submit' name="insert" value='Save' class='button'>
</form>
Ajax code is here:
jQuery('#ajax_form').submit(ajaxformdata);
function ajaxformdata()
{
var alldata = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
//url: "/wp-admin/admin-ajax.php?action=signup",
url: "/mywp/wp-admin/admin-ajax.php?action=cruddata",
data: alldata,
success:function(data)
{
alert('Data submited');
},
error: function(errorThrown)
{
alert(errorThrown);
}
});
return false;
}
PHP code is here
<?php
function cruddata()
{
global $wpdb;
$code = $_POST["code"];
$name = $_POST["name"];
$imagesss = basename($_FILES["photo"]["name"]);
$table_name = $wpdb->prefix . "school";
$wpdb->insert(
$table_name, //table
array
(
'code' => $code,
'name' => $name
//'image_name' => $imagesss
);
$message.="Data inserted";
}
add_action( 'wp_ajax_cruddata', 'cruddata' );
Try this - On your JS your url should be ajaxurl, and action should be cruddata Hope this will works fine.
Register a method that perform your functionality
add_action('wp_ajax_cruddata', 'cruddata');
add_action('wp_ajax_nopriv_cruddata', 'cruddata');
Your function defination -
function cruddata() {
// code goes here...
}
Javascript:
jQuery.ajax({
data: {
'action': 'cruddata',
},
dataType: 'json',
type: 'post',
url: ajaxurl,
beforeSend: function () {
//
},
success: function (data) {
//
}
});
I have the following form:
<td>
<input type="text" name='name[]' class="form-control"/>
</td>
<td>
<input type="text" name='mail[]' class="form-control"/>
</td>
<td>
<select name="gender[]" class="form-control">
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</td>
<td>
<input type="date" name='birth[]' class="form-control"/>
</td>
<td>
<input type="number" name='dni[]' class="form-control"/>
</td>
<td>
<input type="number" name='phone[]' class="form-control"/>
</td>
My ajax call when i try to submit my form
$('#form-reserve-list').on('submit', function(e) {
e.preventDefault();
var names = $("input[name='name[]']").serialize();
var mails = $("input[name='mail[]']").serialize();
var genders = $("select[name='gender[]']").serialize();
var births = $("input[name='birth[]']").serialize();
var dnis = $("input[name='dni[]']").serialize();
var phones = $("input[name='phone[]']").serialize();
var _token = $('input[name=_token]').val();
var est_id = $('input[name=est_id]').val();
var event_id = $('input[name=event_id]').val();
var url = 'http://localhost:82/boulevard/public/event/reserve/list';
$.ajax({
type: 'POST',
url: url,
data: {names:names, mails:mails, genders:genders, births:births, dnis:dnis, phones:phones, _token: _token, est_id:est_id, event_id:event_id},
cache: false,
success: function(data){
alert(data);
}
});
I want to receive this in my Controller and do a foreach or for loop and save it to my db, but the problem is when i try:
$names = Input::get('names'); //from ajax names
foreach($names as $name){
$name[];
//also tried $name[$key] after i added $key =>
}
am i doing something wrong? thank you for the help.
EDIT:
when i do alert($names) in ajax it shows as name%5B%D=carlos&name%5B%D=kevin is this the way its suppose to be? i also did dd($names); and also shows name%5B%D=carlos&name%5B%D=kevin but when i use foreach loop as mentioned above, the chrome console shows me internal error 500, am i suppose to use foreach?
EDIT2:
when i do dd(Input::all())
name%5B%5D=carlos&name%5B%5D=mendieta&name%5B%5D=cordero
how do i loop thru these?
//No need to serialize each field.
//You could do it like this:
$('#form-reserve-list').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
var url = 'http://localhost:82/boulevard/public/event/reserve/list';
$.ajax({
type: "POST",
url: url,
data: formData,
dataType: "json",
success: function(data) {
},
error: function(){
alert('opps error occured');
}
});
});
I have searched very long for a solution to this problem but could not find any.
I get data from the database to show some projects on my website. For each project i can click on a pen-symbol to edit the name of the project. I´d like to send the date per ajax request, but always get the data of the first project. If i try for example to edit the name of the second project "test", i get the data of the first project "blubb"
What i have tried:
- Used classes not Id´s
Call Ajax function from PHP foreach with form
- Used $this
Get Ajax variable from the PHP foreach loops
My code lookes like this (simplified):
< script type = "text/javascript" >
$(document).ready(function() {
$(".submit").click(function() {
//here are the problems, i only get the value of the first project
var new_project_name = $('.new_project_name').val();
var old_project_name = $('.old_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
old_project_name: old_project_name,
new_project_name: new_project_name,
name: name
},
}).
done(function(response) {
blabla
});
});
}); < /script>
<?php foreach($db->query('SELECT * FROM portfolio ORDER BY position, id desc') as $row) { $name = $row['name']; ?>
<div class="rename">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Projektname:</td>
</tr>
<tr>
<td>
<input type="text" class="new_project_name" value="<?php echo $name;?>">
</td>
<input type="text" class="old_project_name" value="<?php echo $name;?>" hidden>
</tr>
<tr>
<td>
<input class="submit" type="submit" value="Umbenennen">
</td>
</tr>
</table>
</div>
<?php } ?>
Thank you for any help.
you could pass the id of the project to ajax and update the new value. For that you just need to pass the id of the element.
HTML
<input type="text" class="new_project_name" value="<?php echo $name;?>" rel="<?php echo $id; ?>">
jQuery
$(document).ready(function() {
$(".submit").click(function() {
var parentObj = $(this).closest('.rename');
var id = parentObj.find(' .new_project_name').attr('rel');
var project_name = parentObj.find(' .new_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
project_name : project_name ,
id:id
},
}).
done(function(response) {
blabla
});
});
});
See the Fiddle and check console
http://jsfiddle.net/hoja/2caukhvo/11/
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 ?>