How can I make multiple ajax in one function? - javascript

My array for add query... The Addquery works for the first table (tb_empgrocery) but the Savequery doesn't work for the second table (tb_empgroc_master).
function saveme(){
var data = new Array();
$('#cLoanOut2 > tbody > tr').each(function() {
var nodes = $(this).children();
var itemno = nodes[0].innerHTML,
qty = nodes[2].innerHTML,
unitprc = nodes[3].innerHTML,
amt = nodes[4].innerHTML;
data.push({
name: "itemno[]",
value: itemno
},{
name: "qty[]",
value: qty
},{
name: "unitprc[]",
value: unitprc
},{
name: "amt[]",
value: amt
});
});
return data;
}
This is my function and I want to call the Save function in my PHP file. Can I do 2 ajax call in one function? The first ajax call works fine on the first table but the 2nd ajax call can't receive the data to the 2nd table. My 1st table is tb_emgrocery and the other one is tb_empgroc_master
$('#OKBtn2').click(function(){
$('#myModal2').modal('hide');
var itemid = $('#main-form2 .active').attr('id'),
qty = $('#main-form2 #'+itemid+' td:eq(2)').text(),
unit_price = $('#main-form2 #'+itemid+' td:eq(3)').text(),
amount = $('#main-form2 #'+itemid+' td:eq(4)').text();
bootbox.confirm("Are you sure?","No","Yes",function(r){
if(r) {
var itemno = $('#itemNo').val();
var data = saveme();
data.push({
name: "todo",
value: "Add"
});
console.log(data);
$.ajax({
url : url,
type : "POST",
async : false,
data : data,
success:function(result){
bootbox.alert('Ordered',function(){
});
updateTable();
}
});
} else {
}
});
//Am I doing right here?
$.ajax({
url : url,
type : "POST",
async : false,
data : {
todo:"Save"
}
});
});
This is my PHP file
case "Add":
$itemno = $_POST['itemno'];
$qty = $_POST['qty'];
$unitprc = $_POST['unitprc'];
$amt = $_POST['amt'];
$coopmemid = $_SESSION['kiosk']['is_coopmemID_kiosk'];
for($x=0; $x<count($itemno); $x++) {
$Addquery = "INSERT INTO tb_empgrocery (coopmemID , date_ordered, item_no, qty_ordered, unit_price, amount)
VALUES ('$coopmemid',(NOW()),'$itemno[$x]','$qty[$x]','$unitprc[$x]','$amt[$x]')";
mysql_query($Addquery, $con);
}
break;
case "Save":
if(isset($_POST['Add'])){
$Addquery = "INSERT INTO tb_empgroc_master (date_ordered) VALUES ((NOW()))";
mysql_query($Addquery, $con);
}
break;
Thanks in advance :))

Yes after getting response of first ajax call you can call another ajax.you can do like following:
$.ajax({
url : url,
type : "POST",
async : false,
data : data,
success:function(result){
bootbox.alert('Ordered',function(){
});
updateTable();
//here you can call another ajax request
}
});
Full Code:
$.ajax({
url : url,
type : "POST",
async : false,
data : data,
success:function(result){
bootbox.alert('Ordered',function(){
});
updateTable();
//here you can call another ajax request
//Am I doing right here?
$.ajax({
url : url,
type : "POST",
async : false,
data : {
todo:"Save"
}
});
}
});
If you want to pass todo in first ajax call. Use following:
data.push({
name: "todo",
value: "Add"
todo: "Save"
});

Place them inside of the success: of the one it relies on.
$.ajax({
url: 'http://www.xxxxxxxxxxxxx.com',
data: {name: 'your name'},
dataType: 'post',
success: function(data){
// do stuff
// call next ajax function
$.ajax({ next ajax });
}
});
repeat multiple levels of ajax calls inside each ajax success.

Related

Parsing array multidimension from ajax to controller in codeigniter?

I have a dynamic table and i want to send in controller by ajax. I have code ajax like this :
$(".save").click(function(e){
var items = new Array();
$("#list-item tr.item").each(function () {
$this = $(this)
var ref_item_id = $this.find("#ref_item_id").val();
var ref_pic_id = $this.find("#ref_pic_id").val();
var price= $this.find("#price").val();
var qty= $this.find("#qty").val();
items.push({ ref_item_id : ref_item_id, ref_pic_id : ref_pic_id, price: price, qty : qty});
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<?php echo base_url("transac/save")?>',
dataType: "json",
data: JSON.stringify({'items': items }),
success: function (data) {
var obj = $.parseJSON(data);
alert(obj.lenth);
},
error: function (result) { alert(result); }
});
})
now, how get data in controller and save in table database. My Controller like this :
public function penjualan_save(){
$items = $this->input->post("items");
// next code ???
}
I hope you can help me. Thanks
first thing, your don't need JSON.stringify({'items': items }), just use:
data: {'items': items },
and in your controller, just create a model and pass your post data into it, for example:
public function penjualan_save(){
$items = $this->input->post("items");
$this->load->model('model_name');
$this->model_name->insert($items);
}
then you need to define a function for your model, like this:
public function insert($data)
{
// if you didn't call database library in autoload.php
$this->load->database();
$this->db->insert_batch('mytable', $data);
}

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

Updating quantity of multiple field from selections using jQuery

I'm updating quantities in an order form with predefined "packs" from the database. Updating the from fields from the "packs" dropdown in the first function works, but the second function that uses those values and multiplies them by the value in a text input does not update the fields.
Also, when looking at the console output, it looks like the ajax request from the first and second function both run when the quantity input is changed.
jQuery(document).ready(function($) {
$("[id^=packs]").on('change', function() {
var packname = this.value;
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1);
$('#'+lineno+'-size1').attr("value", obj.packdetail[0].size1);
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
//multiply packs
$("[id^=packs_qty]").on('change', function() {
var pack_qty = this.value;
var packname = $(this).attr("data-name");
console.log("qty:"+pack_qty);
console.log("packname:"+packname);
var lineno = this.getAttribute('data-lineno');
console.log("lineno: "+lineno);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>products/pack",
cache: false,
// ContentType : 'application/json',
data: {name: packname},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
console.log(obj);
console.log("size1: "+obj.packdetail[0].size1*pack_qty);
$('#'+lineno+'-size1').attr("value", (obj.packdetail[0].size1*pack_qty));
$('#'+lineno+'-size2').attr("value", obj.packdetail[0].size15*pack_qty);
$('#'+lineno+'-size3').attr("value", obj.packdetail[0].size2*pack_qty);
$('#'+lineno+'-size4').attr("value", obj.packdetail[0].size25*pack_qty);
$('#'+lineno+'-size5').attr("value", obj.packdetail[0].size3*pack_qty);
$('#'+lineno+'-size6').attr("value", obj.packdetail[0].size35*pack_qty);
$('#'+lineno+'-size7').attr("value", obj.packdetail[0].size4*pack_qty);
$('#'+lineno+'-size8').attr("value", obj.packdetail[0].size45*pack_qty);
$('#'+lineno+'-size9').attr("value", obj.packdetail[0].size5*pack_qty);
$('#'+lineno+'-size10').attr("value", obj.packdetail[0].size55*pack_qty);
$('#'+lineno+'-size11').attr("value", obj.packdetail[0].size6*pack_qty);
$('#'+lineno+'-size12').attr("value", obj.packdetail[0].size65*pack_qty);
$('#'+lineno+'-size13').attr("value", obj.packdetail[0].size7*pack_qty);
$('#'+lineno+'-size14').attr("value", obj.packdetail[0].size75*pack_qty);
$('#'+lineno+'-size15').attr("value", obj.packdetail[0].size8*pack_qty);
$('#'+lineno+'-size16').attr("value", obj.packdetail[0].size85*pack_qty);
$('#'+lineno+'-size17').attr("value", obj.packdetail[0].size9*pack_qty);
$('#'+lineno+'-size18').attr("value", obj.packdetail[0].size95*pack_qty);
$('#'+lineno+'-size19').attr("value", obj.packdetail[0].size10*pack_qty);
$('#'+lineno+'-size20').attr("value", obj.packdetail[0].size105*pack_qty);
$('#'+lineno+'-size21').attr("value", obj.packdetail[0].size11*pack_qty);
$('#'+lineno+'-size22').attr("value", obj.packdetail[0].size115*pack_qty);
$('#'+lineno+'-size23').attr("value", obj.packdetail[0].size12*pack_qty);
$('#'+lineno+'-size24').attr("value", obj.packdetail[0].size125*pack_qty);
}
catch(e) {
console.log('Exception while request..');
}},
error: function(){
console.log('Error while request..');
}
});
});
});
can you please convert obj.packdetail[0].size1 and pack_qty in to Number and try,
for this you can use
parseInt(obj.packdetail[0].size1) * parseInt(pack_qty);
Please have a try..

Serialzing form and posting ajax to function

I am trying to pass the form field values to a php function located into a file. The problem is that I can't understand how to pass that serialized form data to the function from this ajax to a function in php.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
$('#insert_news').serialize(); // how do I add this data here?
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
This ajax passed the values to the file ajax.php right beyond. And from ajax.php is called the function located in functions.php.
ajax.php
if (isset($_POST['action']) && $_POST['action'] == 'insert_news') {
$cp->insert_into_table('newss', array(
'NewsTitle' => $_POST['title'],
'NewsDescrption' => $_POST['description'],
'Date' => date('Y-m-d H:i:s'),
'status' => '1'
)
);
}
function.php
public function insert_into_table($table_name, array $data){
foreach($data as $col=>$value) {
$cols[] = $col;
$values[] = '\''.$value.'\'';
}
$cols = implode(', ', $cols);
$values = implode(', ', $values);
$this->db->query("INSERT INTO $table_name ($cols) VALUES ($values)");
echo "INSERT INTO $table_name ($cols) VALUES ($values)";
}
The issue is serialize() produces a URL encoded key value paired string, so you can't mix that with your data object.
You can use serializeArray() to get an array of objects, representing the form elements, then iterate over them and add them to a data object:
var data = { action: 'insert_news' };
$.each($('#insert_news').serializeArray(), function(){
data[this.name] = this.value;
});
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: data,
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
Side note: your PHP code is vulnerable to SQL Injection. Consider using a Prepared Statement instead of concatenating user input into the SQL.
You can pass serialized data via ajax to a function the way you are doing but your code needs slight modification.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
serializedData: form // use variable to assign data here
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
I think you can use alternate like this
First : add hidden input for action on your form
<input type="hidden" name="action" value="insert_news"/>
Then your ajax post like this
$('#insert_news').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: $(this).serialize(), // $(this) is from <form id="insert_news">
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
And then use print_r on your ajax.php
print_r($_POST);
$('#insert_news').submit(function(event) {
var name = $("#t1").val();
var pass = $("#t2").val(); //add more var as u need
var key = 0;
var formName = new FormData();
formName.append(key++,name)
formName.append(key++,pass) //append the the var to formdata
$.ajax({
url : 'includes/ajax.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formName,
type : 'post',
success : function(data){
$('#message').html(data).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
this works fine for me :-)

ajax to pass array value , how to fetch array on called page

I have array containg image path ,
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
I am trying to pass this array with following code,
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: "sample value"
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
sample value is passed successfully , but how can i pass array to ajax and use it on another page?? i tried passing array and using with below code but it is not working
$data1 = $_REQUEST['genRep'];
echo "tested".$data1[0];
Try like
genRep = [];
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: GenerateReport
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
It will send your array as genRep
try to use json object. in object you can store your images path
var data=[]; // array
var data[0] = 'something';
var data[1] = 'something1';
var data = { 'name': name, 'email' : email, 'contact' : contact, 'type' : type, 'msg' : msg }; // object
$.ajax({
url : 'contact.php',
type : 'POST',
data : {contact:JSON.stringify(data)}, // for json object
data : {contact: data}, // for array
success : function (msg)
{
alert(msg);
}
})
contact.php
$info = $_POST['contact'];
$info = json_decode($info,true); // for json object
echo $info.name; // for json object
echo $info[0]; // will print something...
$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";
echo json_encode ($arr);
use this on the php page
and use the following to get the output
success:function(msg){
id_numbers = JSON.parse(msg);
alert(id_numbers)
}
Try:
$.ajax({
url: "generatePdf.php",
type: 'POST',
data: form_data,
dataType:"json",
success: function(data) {
alert(data[0]);
}
On the PHP side, you'll be wanting to print:
print json_encode($photos);
Made Some Change
print json_encode(array("photolist"=>$photos));
Then on the server, you'd access these with:
data.photolist[0]; //First photo
I have tested it, this will definitely work !
JS:
var GenerateReport = [];
GenerateReport[0] ="../images/Desert1.jpg";
GenerateReport[1] ="../images/Desert2.jpg";
GenerateReport[2] ="../images/Desert3.jpg";
GenerateReport[3] ="../images/Desert4.jpg";
GenerateReport[4] ="../images/Desert5.jpg";
$.ajax({
type: 'POST',
url: 'generatePdf.php',
data: 'image_array='+GenerateReport,
success: function(msg) {
alert(msg);
}
});
generatePdf.php :
<?php
$image_string = $_POST['image_array'];
$image_array = explode(",", $image_string);
print_r($image_array);
?>
Then you can loop over the $image_array to get the values.
try this
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
corrected code:
var imagedata = '';
$.each(GenerateReport,function(index,value))
{
if(imagedata=='')
{
imagedata = imagedata +'image'+index+'='+value;
}
else
{
imagedata = imagedata +'&image'+index+'='+value;
}
});
$.ajax({
type: "POST",
url: "generatePdf.php",
data: imagedata //pass string imagedata
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
imagedata should have sting like this:
image1=../images/Desert1.jpg&image2=../images/Desert2.jpg and so on
if(isset($_REQUEST['genRep']))
{
$data = $_REQUEST['genRep'];
print_r($data1);
echo "tested".$data1[0];
createPdf($data);
}
My code was correct , there was no value on index 0 , thats why it was not printing anything .My Mistake !!!

Categories

Resources