I have html form that allowed to insert multiple input. I am able to insert only first input. How to insert multiple value in php passing through ajax, My HTML form is as below.
<tr>
<th>ID</th>
<td><input type="number" id="navid"></td>
</tr>
<tr>
<th>Menu IN</th>
<td><input type="text" name="menuin"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng"></input>
</td>
</tr>
User can add input field dynamically(dynamic add has be done by jquery)
It is not problem to pass if only one input group. But I want to pass multiple input if user add more than one.
And I've passed value as
$("#submit").click(function(){
var navid = $("#navid").val();
var menuin = $("input[name='menuin']").val();
var menueng = $("input[name='menueng']").val();
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {navid:navid,menuin:menuin,menueng:menueng},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});
I've inserted input values passed by ajax as below
if (isset($_POST["navid"]) && !empty($_POST["navid"])) {
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menuin',$_POST["menuin"]);
$query1->bindParam(':menueng',$_POST["menueng"]);
$query1->bindParam(':navid', $_POST["navid"]);
$query1->execute();
$msg1 = 'Menu has inserted';
}
Now I want to insert multiple values. How to do ?
You have to apply array in input field for multiple input element. And pass array through ajax and insert to database using foreach loop.
HTML
<tr>
<th>ID</th>
<input type="number" name="navid[]" id="navid">
</tr>
<tr>
<th>Menu IN</th>
<td><input type="text" name="menuin[]"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng[]"></input>
</td>
</tr>
Ajax
$("#submit").click(function(){
var navid = [];
$('input[name="navid[]"]').each( function() {
navid.push(this.value);
});
var menuin = [];
$('input[name="menuin[]"]').each( function() {
menuin.push(this.value);
});
var menueng = [];
$('input[name="menueng[]"]').each( function() {
menueng.push(this.value);
});
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {navid:navid,menuin:menuin,menueng:menueng},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});
PHP
foreach ($_POST["navid"] AS $key => $item){
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menuin',$_POST["menuin"][$key]);
$query1->bindParam(':menueng',$_POST["menueng"][$key]);
$query1->bindParam(':navid',$item);
$query1->execute();
$msg1 = 'Menu has inserted';
}
HTML:
<form id="the_form">
<tr>
<th>ID</th>
<td><input type="number" name="navid[]" id="navid"></td>
</tr>
<tr>
<th>Menu IN</th>
<td><input type="text" name="menuin[]"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng[]"></input>
</td>
</tr>
<input type="submit" value="Submit Form" id="submit"/>
</form>
I added a name for your ID so that it will be included when you submit the form, I just added a form tag since it was not present in your question.
JS:
Read about serialize
(https://stackoverflow.com/questions/15173965/serializing-and-submitting-a-form-with-jquery-post-and-php)
$("#submit").click(function(){
var form_data = $("#the_form").serialize();
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {form_data:form_data},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});
PHP
//Since the submitted data is now a collection of an array you'll have to loop through it to save them in the database as you cannot save an array directly in a DB.
if (!empty($_POST["navid"])) {
for($counter = 0; $counter < sizeof($_POST["navid"]); $counter++){
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
$query1->bindParam(':menuin',$_POST["menuin"][$counter]);
$query1->bindParam(':menueng',$_POST["menueng"][$counter]);
$query1->bindParam(':navid', $_POST["navid"][$counter]);
$query1->execute();
$msg1 = 'Menu has inserted';
}
}
Related
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.
I have a form where I am selecting a product. On the basis of the selected product, I want to update the rest of the fields in the form.
The Form display with select option
On selecting the product name, I want rest of the details of the form to fill up from the database using php.
Here is the code for the table created.
<table id="productTable" class="table-c">
<tr>
<th class="text-center" style="width: 5%;">SR No.</th>
<th class="text-center" style="width: 45%">DESCRIPTION</th>
<th class="text-center" style="width: 10%">HSN/SAC</th>
<th class="text-center" style="width: 10%">QTY IN-HAND</th>
<th class="text-center" style="width: 10%">ENTER OUTWARD QTY</th>
<th class="text-center" style="width: 5%">Delete</th>
</tr>
<tr style="text-align: center;" id="products">
<?php $j=0; $j++; ?>
<td><?php echo $j; ?></td>
<td><select class="form-control" name="code" id="productID" style="width: 429px;">
<?php
$sql = "SELECT * FROM `product`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option id='".$row['code']."' value='".$row['pname']."'>".$row['pname']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
<td><input type="number" name="hsnNo" id="hsnNo" readonly></td>
<td><input type="number" name="qty" id="qty" readonly></td>
<td class="coljoin"><input type="number" format="2" name="amount"></td>
<td>
<span class="fa fa-trash"></span>
</td>
</tr>
</table>
How should I do this?
This is PHP Code:-
<form>
<select name="customer" id="customer_id">
<option value="">-- Select customer Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
Address: <input name="add" type="text" value="">
Mobile: <input name="mobile" type="text" value="">
EMail-Id:<input name="email" type="text" value="">
</form>
This is JS Code:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#customer_id").change(function() {
var id = $(this).val();
var dataString = 'cid='+id;
//alert(dataString);
$.ajax({
url: 'dataAjax.php',
type: 'post',
data: dataString,
success: function(response) {
// Parse the jSON that is returned
var Vals = JSON.stringify(response);
// These are the inputs that will populate
$("input[name='add']").val(Vals.add);
$("input[name='mobile']").val(Vals.mobile);
$("input[name='email']").val(Vals.email);
}
});
});
});
</script>
This is other PHP File Code:-
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("add"=>'India',"mobile"=>'1234567890','email'=>'demo#demo.com'));
}
?>
using product id use ajax & call the get_product_details(id) & in get product convert response array in json & echo it .in ajax, response data you have to parse in json... then set you required field.. (add require js)
**Ajax Call :**
$(document).on('change','your_dropdown_filed_id',function()
{
var product_id = $(this).val();
//Ajax call
$.ajax({
method: "POST",
url: "/get_product_details", //your php file function path
data: { product_id: product_id}
}).done(function( response ) {
alert( "Data Saved: " + response );
var obj = JSON.parse(response);
//obj hold all values
alert(obj.qty);
alert(obj.hsn);
$('#hsn_id').val(obj.hsn);
$('#qty_id').val(obj.qty);
});
});
**product.php**
function get_product_details(product_id)
{
//Get product details in associative array format
echo json_encode($product_details);
}
Once the product is selected execute ajax request and get data from the database with respective of the selected product.
JAVASCRIPT CODE :
$('#products').change(function(){
$.ajax({
url: 'your php code page name which returns product details.php?product_id'+$('#products').val(),
type: 'post',
success: function(response) {
var obj = JSON.parse(response);
$("#hsn_sac").val(obj.hsn_sac); // hsn or sac values
$("#qty_in_hand").val(obj.qty_in_hand); // qty_in_hand values
}
}});
});
PHP CODE :
<?php
// first connect database and then fire the query to get product details
$connection = mysql_connect("your database host name","database username","database password","database name");
$result = mysql_query("your query");
while ($row = mysql_fetch_array($result)) {
// get data and store in array
}
mysql_close($connection); // close connection
echo json_encode(database result); // encode database result so that it will available to ajax request and assign back to view
exit;
?>
I have a table that generating dynamic raw's, I need to send through ajax post to receive from PHP. Below I have given all my selected codes, this is not working.
In console showing as
PHP ERROR: Undefined index all_ch_no, all_yd_stock_no, all_comments
HTML FORM, below table rows are dynamically generated through ajax, if I place static table data, then it's working! How can I solve?
<form method="post" id="customer_do_add">
<input type="text" id="phone_no" name="phone_no">
<table class="table" id="group_cars">
<thead>
<tr>
<th style="width: 20%;">Chassis No</th>
<th style="width: 15%;">Yard Stock No</th>
<th style="width: 50%;">Comments</th>
<th style="width: 15%;">Remove</th>
</tr>
<tr>
<td><input type="text" class="waz" value="DD51T-224534" name="all_ch_no[]"></td>
<td><input type="text" class="waz" value="77832" name="all_yd_stock_no[]"></td>
<td><input type="text" class="waz" value="Test3" name="all_comments[]"></td>
</tr>
<tr>
<td><input type="text" class="waz" value="DD51T-45354" name="all_ch_no[]"></td>
<td><input type="text" class="waz" value="123123" name="all_yd_stock_no[]"></td>
<td><input type="text" class="waz" value="Test" name="all_comments[]"></td>
</tr>
...
</thead>
</table>
</form>
jQuery:
$('#customer_do_add').on('submit', function(e) {
e.preventDefault();
var val = $('#customer_do_add').serializeArray();
$.ajax({
url: "auction/customer_do_add/",
data:val,
type: "POST",
success: function (responseText, statusText, xhr, $form) {
result = $.parseJSON(responseText);
}
});
return false;
});
PHP
public function customer_do_add(){
print_r($_POST);
exit;
}
Printing Only Phone number, Arrays are not printing
Array
(
[phone_no] => 123456
)
Send data params in Jquery call then only you can receive post
$('#customer_do_add').on('submit', function(e) {
e.preventDefault();
var val = $('#customer_do_add').serializeArray();
$(this).ajaxSubmit({
url: "auction/customer_do_add/",
data: val,
success: function (responseText, statusText, xhr, $form) {
result = $.parseJSON(responseText);
}
});
return false;
});
Your $_POST is empty because jQuery.ajax() will pass data as GET data (it's being appended to the url). Setting the method arg to post will fix this.
$.ajax({
url: "/auction/customer_do_add/",
data: val,
success: function (data) {
console.log(data);
},
dataType: 'json',
method: 'POST',
});
You could also use jQuery.post() for a simplified syntax;
$.post({
url: "/auction/customer_do_add/",
data: val,
success: function (data) {
console.log(data);
},
dataType: 'json'
});
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 want to get results from 2 table using SQL INNER JOIN but it's only showing 1st result not others one. If i select other data then it's showing following error message:
Warning: Invalid argument supplied for foreach() in D:\software installed\xampp\htdocs\contact-management\getContactDetails.php on line 14[]
Description of my functionality:
I have 2 table in my database.
contact_details:
cdid, family_name, given_name, work_phone, mobile_phone, email, email_private, cid
contact_docs:
docid, cdid, file_name, file_des
I'm showing all contacts (only family_name) from database. After select each contacts then it's showing/loading all contact details using Jquery/ajax which is showing on a HTML FORM. So now it's showing contact_details data on the html input type = text field. But I also need show contact_docs data which is actually files.
So when I send a request to the server using jQuery/ajax I've to use SQL inner join query to get the result from both table based on id (cdid). But unfortunately my inner join query is not working properly. It's not showing all contact details data on the html form if I select different contacts. Only showing 1st result.
My questions are:
How do I fix this inner join query?
How do I show the uploaded file on the form (file link would be better) when whole form is load with all data from 2 table ?
Note: I can successfully edit/insert the data to database but issue about showing the data with file.
This is my code:
Html page:
<div id="showContactsDetails">
<h2>Individual Record Details</h2>
<div style=" visibility:hidden;" id="visiable">
<span class="mandatory"><sub>* Required</sub></span>
<!--success update -->
<div id="success"></div>
<form action="" method="post" enctype="multipart/form-data" id="all_contact_details">
<table width="450" border="0" cellspacing="0" cellpadding="0">
<input type="hidden" name="cdid" id="cdid"/>
</tr>
<tr>
<td>Company Name</td>
<td><input type="text" name="company_name" id="company_name" disabled="disabled"/></td>
</tr>
<tr>
<td>Family name</td>
<td><input type="text" name="family_name" id="family_name"/></td>
</tr>
<tr>
<td>Given name</td>
<td><input type="text" name="given_name" id="given_name"/></td>
</tr>
<tr>
<td>Work Phone</td>
<td><input type="text" name="work_phone" id="work_phone"/></td>
</tr>
<tr>
<td>Mobile Phone</td>
<td><input type="text" name="mobile_phone" id="mobile_phone"/></td>
</tr>
<tr>
<td>Email address</td>
<td><input type="text" name="email" id="email"/></td>
</tr>
<tr>
<td>Private email address</td>
<td><input type="text" name="email_private" id="email_private"/></td>
</tr>
<tr>
<td>Upload your document</td>
<td><input type="text" name="file_des_1" id="file_des1" placeholder="short description of your document" class="shor"/><span class="mandatory"><sup>*</sup></span></td>
<tr>
<td></td>
<td align="left"><input name="file1" type="file" id="file" class="file"/></td>
<span class="file_des_1"></span>
</tr>
<tr>
<td></td>
<td><input type="text" name="file_des_2" id="file_des2" placeholder="short description of your document" class="shor"/><span class="mandatory"><sup>*</sup></span></td>
<tr>
<td></td>
<td align="left"><input type="file" name="file2" id="file_2" class="file"/></td>
</tr>
<tr>
<td></td>
<td><input type="text" name="file_des_3" id="file_des3" placeholder="short description of your document" class="shor"/><span class="mandatory"><sup>*</sup></span></td>
<tr>
<td></td>
<td align="left"><input type="file" name="file3" id="file_3" class="file"/></td>
</tr>
<tr>
<td></td>
<td><input type="text" name="file_des_4" id="file_des4" placeholder="short description of your document" class="shor"/><span class="mandatory"><sup>*</sup></span></td>
<tr>
<td></td>
<td align="left"><input type="file" name="file4" id="file_4" class="file"/></td>
</tr>
<tr>
<td> </td>
<td><input type="button" name="submit" value="Update Details" class="submit" id="upload"/></td>
</tr>
</table>
</form>
</div>
</div><!--showContactsDetails-->
jQuery/Ajax page:
//edit the form....................
<script>
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'editContactDetails.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
$("#success").html(data);
document.getElementById("all_contact_details").reset();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
//load the html form with all contact details..................................................
function getDetails(id) {
id = id;
$.ajax({
url: 'getContactDetails.php',
type: 'post',
data: {'id' : id},
dataType : 'json',
success: function( res ) {
document.getElementById("visiable").style.visibility = "visible";
console.log(res);
$.each( res, function( key, value ) {
console.log(key, value);
$('input[type=text][name='+key+']').val(value);
$('input[type=hidden][name='+key+']').val(value);
$('textarea[name='+key+']').val(value);
});
}
});
}
</script>
Php page (getContactDetails.php):
<?php
ob_start();
require_once("config.php");
$id = (int) $_POST['id'];
$sql = mysql_query("SELECT contact_details.cdid, contact_details.family_name, contact_docs.file_name FROM contact_details INNER JOIN contact_docs ON contact_details.cdid = contact_docs.cdid WHERE contact_docs.cdid = '$id'");
$res = mysql_fetch_array($sql);
$data = array();
foreach( $res as $key => $value ) {
$data[$key] = $value;
}
echo json_encode($data);
?>
I'm a new in web development field. So may be my code is wrong that's why your help is greatly appreciated :)
I think you want something like this... (using deprecated API)
<?php
require_once("config.php");
$id = (int) $_GET['id'];
$query = "
"SELECT c.cdid
, c.family_name
, d.file_name
FROM contact_details c
JOIN contact_docs d
ON c.cdid = d.cdid
WHERE d.cdid = $id
";
$result = mysql_query($query);
$data = array();
while ($res = mysql_fetch_array($result)){
foreach( $res as $key => $value ) {
$data[$key][] = $value;
}
}
echo json_encode($data);
?>