Jquery ajax POST label/value pair - php

I want to pass label/value pair in Ajax .POST but cannot find any solution. Ajax .POST normally send id/value pair but I cannot change my id and would like to send labels/value pair instead. I have provided partial form. Any help please.
$.ajax({
url:"allfields.php",
type:"POST",
// dataType:"json",
data: $("#frmRequest").serialize(),
success: function(msg){
alert("Form Submitted: "+ msg);
return msg;
},
error: function() {
alert('Error occured');
}
});
<body>
<form id="frmRequest" name="frmRequest" >
<div class="clearfix" id="idRequestDetails" >
<table width="809" border="0" id="tbl_data_1_1_1_1__" summary="Profile">
<tr>
<th width="156" scope="col"><label class="labelrequest" for="txtProfileName1__">Name</label>
</th>
<th width="74" scope="col"><label class="labelrequest" for="txtProfileUserID1__">User ID</label></th>
<th width="131" scope="col"><label class="labelrequest" for="txtSiteCost1__">Site Cost Centre</label></th>
<th width="182" scope="col"><label class="labelrequest" for="txtDetail1__">Additional Details</label></th>
</tr>
<tr>
<td><input type="text" name="txtProfileName1__" id="txtProfileName1__" tabindex="100" /></td>
<td><input name="txtProfileUserID1__" type="text" class="clearfix" id="txtProfileUserID1__" tabindex="110" size="8" /></td>
<td><input name="txtSiteCost1__" type="text" id="txtSiteCost1__" tabindex="220" size="8" /></td>
<td><textarea name="txtDetail1__" rows="1" id="txtDetail1__" tabindex="240"></textarea></td>
</tr>
</table>
</div>
</body>

Here is an example:
HTML
<form>
<label>Label1</label><input type="text" value="1">
<label>Label2</label><input type="text" value="some">
</form>
jQuery
var dataToServer = [];
$('form label').each(function() {
dataToServer.push({
label: $(this).text(),
value: $(this).next().val()
});
});
console.log(data);
// output
// [ {label: 'Label1', value: '1'}, {label: 'Label2', value: 'some'}]
Working Example.
Hope this can give you some guideline.
According to commnet
AJAX part
$.ajax({
url: "allfields.php",
type: "POST",
dataType:"json",
data: dataToServer, // send above data here
success: function(msg) {
alert("Form Submitted: " + msg);
return msg;
},
error: function() {
alert('Error occured');
}
});
Final shot
$('#submit').on('click', function() {
var dataToServer = [];
$('#frmRequest label').each(function(i, el) {
var temp= {},
label = $(this).text(),
value = $('#' + $(this).attr('for')).val();
temp[label] = value;
dataToServer.push(temp);
});
console.log(dataToServer);
});
See the console output

Related

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.

Number input and jquery [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I have this table:
<table id="product" class="table table-bordered table-striped">
<thead>
<tr>
<th>Id</th>
<th>Cantidad</th>
<th>Producto</th>
<th>Marca</th>
<th>Precio</th>
<th>Importe</th>
<th>Serial</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I add rows to that table with this jquery code:
$( "#name" ).autocomplete({
source: 'http://sosacelulares.com/index.php/product/search',
minLength: 1,
select: function (event, ui) {
var value = ui.item.value;
var data1 = value.split("-");
var data = data1[0].split(" ");
$( "#product" ).show();
var v = data[1];
$.ajax({
async:true,
type: "POST",
dataType: "html",
contentType: "application/x-www-form-urlencoded",
url:"http://sosacelulares.com/index.php/product/get",
data:"id="+v,
success: function(response) {
var returnedData = JSON.parse(response);
$("#product > tbody").append('<tr><td>' + returnedData[0].id_product + '</td><td><input min="1" type="number" style="width: 100px;" value="" class="form-control quantity" id="quantity" placeholder="Cantidad" required></td><td>' + returnedData[0].name + '</td><td>' + returnedData[0].brand + '</td><td><input type="text" style="width: 100px;" value="' + returnedData[0].buy_price + '" class="form-control" placeholder="Precio" required></td><td></td><td><button type="submit" class="btn btn-success">Agregar Serial</button></td></tr>');
}
});
},
});
I just look for a name in a text input and then when I find it I just add it to the table. The problem is that the rows that I am adding they have a number input field that it is to add the quantity I test it like this:
$(".quantity").change(function () {
alert(1);
});
I do not know why if I change the quantity input that it is ubicated within the new row that i added with jquery it does not work, if I make a change the alert does not appear, what am I doing bad? Thanks!
Try this:
$(document).on("change", ".quantity", function () {
alert(1);
});

Dynamically generated ajax data Post from jQuery to PHP

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'
});

How to send multiple same name input fields value via ajax post method

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

Assigning AJAX response for two separate DIV tags

This is my ajax call code..
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
alert(data)
$("#desc").val(data);
$("#bal").val(data);
}
});
});
});
</script>
include "db.php";
$itemcode=$_POST['itemcode'];
$sql="select * from itemmaster where Item_Code='$itemcode'";
$result = mysql_query($sql, $con);
while($row = mysql_fetch_array($result)) {
echo $row['Item_Desc'];
echo $row['Balance_Stock'];
}
This is simple html form..
<form action="add.php" method="post">
<table style="border: 1px solid black;padding:20px;"cellspacing="1px">
</br></br>
<tr>
<td>Issue No:</td> <td><input name="issueno" type="text" id="issueno"/></td>
<td>Issue Date:</td> <td><input name="issuedate" type="date" id="issuedate"/></td></tr></br></br><tr></tr>
<tr>
<td>Item Code:</td> <td><input name="itemcode" type="text" id="itemcode" /></td>
<td>Description:</td> <td><input name="des" type="text" style="width:250px; height:23px" id="desc"/></td>
<td>Bal Quantity:</td> <td><input name="bal" type="text" id="bal"/></td>
</tr></br>
<tr> <td>Issue Quantity:</td> <td><input name="issuequ" type="text" id="issuequ"/></td></tr></br><tr></tr>
<tr><td>Remark:</td> <td><input name="remark" type="text" style="width:250px; height:23px" id="remark"/></td></tr></br>
<tr><td colspan="6"><center><input type="submit" value="submit"></center></td></tr>
</table>
</form>
When I alert(data) I am getting this samsung20.00. where samsung is description and 20.00 is bal. I want to assign description desc id an bal to bal id. So How do I do that??
In your ajax.php file, you need to use json_encode function so you can parse it after get response:
include "db.php";
$itemcode=$_POST['itemcode'];
$sql="select * from itemmaster where Item_Code='$itemcode'";
$result = mysql_query($sql, $con);
while($row = mysql_fetch_array($result)) {
$json = array("Item_Desc" = > $row['Item_Desc'],
"Balance_Stock" => $row['Balance_Stock']
);
}
echo json_encode($json);
After making adjusts that you can encode your response, Your ajax need to parse it.
Example:
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
var obj = JSON.parse(data);
$("#desc").html(obj.Item_Desc);
$("#bal").html(obj.Balance_Stock);
}
});
});
});
Its very simple.
Hope it helps you
in your php file join the value Samsung and 20.00 with || sign
include "db.php";
$itemcode=$_POST['itemcode'];
$sql="select * from itemmaster where Item_Code='$itemcode'";
$result = mysql_query($sql, $con);
while($row = mysql_fetch_array($result)) {
echo $row['Item_Desc'].'||'.$row['Balance_Stock'];
}
java script code add the var response = data.split('||'); function
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
alert(data)
var response = data.split('||');//spilt the value
$("#desc").val(response[0]);
$("#bal").val(response[1]);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#itemcode').blur(function(){
var itemcode = $(this).val();
$.ajax({
type: "POST",
url:'ajax.php',
data: {'itemcode' : itemcode} ,
cache: false,
success: function(data) {
alert(data)
var str1 = data.replace(/\d.+/g, '');
var str2 = data.replace(/[^\d.-]/g, '');
$("#desc").val(str1);
$("#bal").val(str2);
}
});
});
});
</script>

Categories