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) {
//
}
});
Related
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
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.
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;
});
I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display
I have a simple ajax (jquery version) script and very short php function and they works fine without problem.
When I submit the value from the form input are, the ajax will work to send and get result from
the php script, in this case to get a total amount of the book order.
The Ajax script and html section are as follows:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get field value
var qtyVal = $('#qty').val();
// use HTTP GET get ajax
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
//get xml value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
<body>
Total price:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<form>
<p>
<label>quantity: </label>
<input type="text" id="qty" name="qty"/>
<br/>
<input type="submit" value="submit">
total price:</p>
<p> </p>
</form>
And the following php script serving as xml also works fine with above ajax request:
<?php
// XML document
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
echo "<?xml version=\"1.0\" ?>";
echo "<datetime>";
echo "<qty>" . $qty*100 . "</qty>";
$total=$qty*100;
if ($total==0)
echo "<caution>"."please input number!"."</caution>";
else if ($total<=500)
echo "<caution>"."you shoud buy more!"."</caution>";
echo "";
echo "</datetime>";
?>
However when I combine the above scripts with my shopping cart foreach loops, it doesn't work and the ajax script failed to get variables from the form input area. I don't know if it is a variable scope issue (globals or local)? or anything else?
The following is the total script I would like to fixed with:
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
// get value from the form
var qtyVal = $('#qty').val();
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<table border="1" align="center">
<tr>
<th>no</th>
<th>name</th>
<th>price</th>
<th>qty</th>
<th>update</th>
</tr>
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<form action="sessionCartUpdate.php">
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" id="qty" name="qty" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="submit" name="qty"
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
</form>
<?php
}
?>
<tr><td colsan="5">total amount:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div></td></td>
</table>
<p>continue to shop
<p>Put your order
</body>
</html>
I would be very grateful if anyone can offer kind or possible suggestion or advice?
My goal is to put different number (variables) in the "input area" (name or id as "qty") throught the using of ajax to get a total amount of price and show the result in the div box (id="result" or "result1").
You should replace the id attribute with class because id is supposed to be unique in the dom and using class you can do a loop to get all quantities of the items in the cart
Another thing i have noticed that you have made the an individual form foreach item in the cart there should be one form having the multiple fields,also remove this line <input type="submit" name="qty" it doesent makes sense
<form action="sessionCartUpdate.php">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td><?php echo $_SESSION["psn"][$i];?></td>
<td><?php echo $_SESSION["pname"][$i];?></td>
<td><?php echo $_SESSION["price"][$i];?></td>
<td><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<td><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr>
<?php
}
?>
</form>
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseout( function() {
var qtyVal =0;
$( ".qty" ).each(function() {
qtyVal =qtyVal + parseInt($(this).val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: { qty : qtyVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('qty').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
// get field values
$qty = (isset($_POST["qty"]) ) ? $_POST["qty"] : $_GET["qty"];
Instead of using both $_GET and $_POST, you can use $_REQUEST which will give data from either POST or GET.