How to find button created by Ajax outside Ajax - php

I am creating table rows with delete button in it, but the problem is I am not able to find that delete button outside Ajax. So I use Ajax inside Ajax logic but I have to do it again and again. I want to use the button created by Ajax to call separate Ajax call.
My script is:
$.ajax({
url : "{{url('addtocart')}}",
type : "POST",
data : {_token: CSRF_TOKEN, username:username, userType:userType,
table_no:table_no, order_no:order_no, cname:cname,
tname:tname, dname:dname, dish_qty:dish_qty,
chefnote:chefnote
},
success : function(data){
//console.log(data);
$('#cartOrder').empty();
for(var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
function drawRow(rowData) {
var row = $("<tr />")
row.empty();
$("#cartOrder").append(row);
row.append($("<td contenteditable='true' onBlur='saveToDb(this, "+rowData.dish+")'>" + rowData.dish + "</td>"));
row.append($("<td contenteditable='true' id='xyz'>" + rowData.dish_qty + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.chefnote + "</td>"));
row.append($("<td>"+"<button class='btn btn-primary' value='"+rowData.ord_id+"'>" +"Edit"+"</button>"+" | " +"<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>" + "</td>"));
}
//delete cart order
$('tBody #deletecart').click(function(e){
e.preventDefault();
$.get("{{url('deletecart')}}",{id:$(this).val()},function(data){
// console.log(data);
$.ajax({
url : "{{url('getcart')}}",
type : 'GET',
data : {table_no:table_no},
success : function(data){
console.log(data);
$('#cartOrder').empty();
for(var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
function drawRow(rowData) {
var row = $("<tr />")
row.empty();
$("#cartOrder").append(row);
row.append($("<td contenteditable='true'>" + rowData.dish + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.dish_qty + "</td>"));
row.append($("<td contenteditable='true'>" + rowData.chefnote + "</td>"));
row.append($("<td>"+"<button class='btn btn-primary' value='"+rowData.ord_id+"'>" +"Edit"+"</button>"+" | " +"<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>" + "</td>"));
}
}
});
});
});
}
});
});
As you can see, first time I use Ajax to load data into table. But when I click delete, the row gets deleted from database but not from the view. So I load that table data on delete button in second Ajax. But it is not working the second time I click the delete button. It is may be because I am calling parent delete function. How can I do this?

The problem is with ID. You can not use same id at multiple places in same page. In your case, you need to use class instead of id.
Replace this :
<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>
with ?
<button class='btn btn-primary' class='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>
As you are creating this html in loop so id is repeating. So use class and override your delete function :
$('tBody .deletecart').click(function(e){

Related

How refresh datatable after ajax success in laravel?

I use datatable to show my data. I store data in ajax request & append that after a successful response. Data is appended successfully. But the problem is datatable is not updated when appending an item. If I reload the page then It works. See image red mark. Data is appended but datatable is not updated.
Here is my ajax success response
success: function(response) {
if (response.status == true) {
var href = "{{ route('home') }}/";
$('#dataTable tbody').prepend( "<tr class='data" + response.data.id + "'>" +
"<td><img src='" + href + "storage/sliders/" + response.data.image + "'></td>" +
"<td>" + response.data.name + "</td>" +
"<td>" + response.data.title+ "</td>" +
"</tr>" );
}
}
How to auto-refresh datatable after ajax success?
try like bellow:-
var table = $('#table_id').DataTable({
//ajax method that gets data from databases.
});
use this method to refresh your table:
table.ajax.reload();
if it gives an error like
DataTables warning: table id=table_id- Invalid JSON response
then use the below function before adding data to the table to solve the error:
table.clear()

ajax send and get back mktime

Hello i m using an ajax function to get back the goog day from a script on my php file ... It' not working i don't understand why,
please help i need ajax dont want to reload each time a date is picked in my php calendar
my HTML is
<p class="texte choixDate"></p>
so my jquery code is
$("#calendrier td a").click(function(){
var jour=$(this).text();
var mois="<?php echo $mois2;?>";
var annee="<?php echo $year;?>";
$.ajax({
url : 'requete.php',
type : 'GET',
data : 'jour='+jour+'&mois='+mois+'&annee='+annee,
dataType : 'text',
success : function(text){ // code_html contient le HTML renvoyé
$(".texte.choixDate").empty();
$(".texte.choixDate").append("<i class='fa fa-arrow-circle-down fa-2x' aria-hidden='true'></i><br/>Vous avez choisi le " + text + " " + jour + " " + mois + " " + annee +"<br/><br/><a class='btn' href='accueil.php?val2=1#agenda1' title='Valider'>Valider</a>");
}
});
});
and my php file is
$semaine = array("Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi","Dimanche");
$mois=$_GET["mois"];
$jour=$_GET["jour"];
$annee=$_GET["annee"];
$moisAtester2= mktime(0,0,0,$mois,$jour,$annee);
$jourSem=$semaine[date("w",$moisAtester2)];
echo $jourSem;
THANKS FOR HELP !!
just use the datetime picker where you can get do that
onClose: function () {
$scope.isSelected = true;
var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
}
Use onClose function to call ajax

Send form row datas to external PHP file

I need some help to resolve a problem.
I'm trying to send some datas from a form ROW to a php file.
Here's the first php code (It's inside an echo and value come from a MySQLi query):
<form id=\"comedivid\" method=\"post\">
<input class=\"numer-qua\" type=\"number\" id=\"dadivid\" min=\"0\" max=".$_GET['qua']." autofocus autocomplete=\"off\" name=\"dadivid\" maxlength=\"4\" size=\"5\">
<input type=\"hidden\" value=\"".$row["id_tes"]."\" name=\"ord\" id=\"ord\">
<input type=\"hidden\" value=\"".$_GET['codice']."\" name=\"cod\" id=\"cod\">
<input type=\"hidden\" value=\"".$_GET['qua']."\" name=\"arr\" id=\"arr\">
<input type=\"hidden\" value=\"".$row['descri']."\" name=\"desc\" id=\"desc\">
<input type=\"hidden\" value=\"".$row['unimis']."\" name=\"um\" id=\"um\">
<input type=\"hidden\" value=\"".$row['quanti']."\" name=\"qua\" id=\"qua\">
<input type=\"hidden\" value=\"".$row['prelis']."\" name=\"pre\" id=\"pre\">
<input type=\"hidden\" value=\"".$row['sconto']."\" name=\"sco\" id=\"sco\">
<input type=\"hidden\" value=\"".$row['codvat']."\" name=\"cva\" id=\"cva\">
<input type=\"hidden\" value=\"".$row['pervat']."\" name=\"iva\" id=\"iva\">
<input type=\"hidden\" value=\"".$row['codric']."\" name=\"ric\" id=\"ric\">
<button id=\"dividili\" class=\"btn btn-blue\" type=\"submit\"><i class=\"fa fa-copy\"> Dividi Riga</i></button>
\n";
The form is included in a table. The query may give more as one result.
Here's my AJAX code:
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var dadivid = $("#dadivid").val();
var ord = $("#ord").val();
var cod = $("#cod").val();
var arr = $("#arr").val();
var desc = $("#desc").val();
var um = $("#um").val();
var qua = $("#qua").val();
var pre = $("#pre").val();
var sco = $("#sco").val();
var cva = $("#cva").val();
var iva = $("#iva").val();
var ric = $("#ric").val();
$.ajax({
type: "POST",
url: "../../modules/acquis/dividi.php",
data: "dadivid=" + dadivid + "&ord=" + ord + "&cod=" + cod + "&arr=" + arr + "&desc=" + desc + "&um=" + um + "&qua=" + qua + "&pre=" + pre + "&sco=" + sco + "&cva=" + cva + "&iva=" + iva + "&ric=" + ric,
success: function(){alert('success');}
});
});
});
It's not working, no data are sent to URL.
Is it because the form is in more rows?
Or is there a mistake in my code?
I tried with serialize also, with no results.
Here's the code:
$("#dividili").click(function(e){
$.ajax( {
type: "POST",
url: "../../modules/acquis/dividi.php",
data: $('#comedivid').serialize(),
success: function( response ) {}
});
});
Thank you so much for your help!
I would suggest using serialize():
$("#dividili").click(function(){
$(this).closest("form#comedivid").submit(function(event) {
event.preventDefault();
var form_data = $('form#comedivid').serialize();
// or
var form_data = $(this).serialize();
// try to output that just to make sure you are doing it right
console.log( form_data );
// or
alert( form_data );
$.ajax({
type : "POST",
url : "../../modules/acquis/dividi.php",
data : form_data,
success : function(){alert('success');}
});
});
Since you already tried that, and if the output is ok, then it's a problem with your PHP, so try to output at the beginning of your file what was received:
<?php
echo '<pre>';
print_r( $_POST );// or $_REQUEST for both $_POST and $_GET
echo '</pre>';
die;
// the rest of your code...
If everything is received well in PHP, you need to make sure you are using the right way to fetch your data, like $dadivid = $_POST["dadivid"];
jQuery 'serialize' method made data like get query form.
so, Data length would be limited in apache configuration.
Try use this custom method.
(function($) {
$.fn.serializeObject = function () {
"use strict";
var result = {};
var extend = function (i, element) {
var node = result[element.name];
if ('undefined' !== typeof node && node !== null) {
if ($.isArray(node)) {
node.push(element.value);
} else {
result[element.name] = [node, element.value];
}
} else {
result[element.name] = element.value;
}
};
$.each(this.serializeArray(), extend);
return result;
};
});
How to use is same default jQuery 'serialize' method.

AJAXing of a form field generated via another AJAX

I have a form created from the following action,
USER selects a link
using $('#livesearch').on('click', 'a', function(e){}); accesses and gets some information from MySQL db through .php via AJAX call
based on the response data, it populates the content div in the bootstrap 3 modal window
in the modal window populated via javascript, I have another form field for submission,
in this form field, I'm trying to do a POST/Response through AJAX call and it just takes me to the php page and not doing anything..
suppose is it not possible to AJAX on a form field dynamically generated by another AJAX call?
to explain in more detail, I've included my codes here below,
for point 3 and 4,
// AJAX call from a link selected
$('#livesearch').on('click', 'a', function(e) {
var selectedValue = $(this).attr("value");
$.ajax({
type: 'POST',
async: true,
url: "../../../avocado/private/functions/measures.php",
data: {name:selectedValue},
success: function(data, status){
var selectedData = JSON.parse(data);
console.log(selectedData);
// populates contents for the modal body
$.each( selectedData, function( i, val ) {
document.getElementById("measures").innerHTML+= "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[i][6]+"</td><td rowspan=\"4\">Quantity"
+ "<form role=\"form\" action=\"../../../avocado/private/functions/food_save.php\" id=\"measure_quantity\" method=\"POST\">"
+ "<div class=\"form-group\">"
+ "<label class=\"sr-only\" for=\"quantity\">quantity</label>"
+ "<input type=\"Number\" name=\"quantity\" class=\"form-control\" id=\"quantity\" placeholder=\"desc"+i+"\">"
+ "<input type=\"hidden\" id=\"food_name\" name=\"food_name\" value=\""+selectedValue+"\">"
+ "<input type=\"hidden\" name=\"food_type\" value=\"nutrients\">"
+ "<input type=\"hidden\" name=\"food_id\" value=\""+selectedData[i][0]+"\">"
+ "<input type=\"hidden\" name=\"measures_id\" value=\""+selectedData[i][4]+"\">"
+ "<input type=\"hidden\" name=\"grams\" value=\""+selectedData[i][10]+"\">"
+ "</div>"
+ "<button type=\"submit\" class=\"btn btn-default\">Save</button>"
+ "</form>"
+ "</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[i][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[i][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[i][9]+"</td></tr>"
+ "<tr><th>(g)</th><td>"+selectedData[i][10]+"</td></tr>"
+ "</table>";
});
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
});
for point 5,
$('#measure_quantity').submit(function(){
postData = $(measure_quantity).serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
Try something like the below:
$( "#measure_quantity" ).on( "submit", function( event ) {
event.preventDefault();
postData = $("#measure_quantity").serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
This will still work with dom elements that do not exist on the initial page load because of the .on() statement.
Also its not something silly like the typo:
postData = $(measure_quantity).serialize();
Should be...
postData = $("#measure_quantity").serialize();
I have found the problem, for dynamically loaded contents such as this case, I have to add a selector parameter otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content
$(document.body).on('submit', '#measure_quantity' ,function(e){
console.log("heeeellllo");
e.preventDefault();
var postData = $("#measure_quantity").serialize();
$.post("../../../avocado/private/functions/food_save.php",postData+'&action=submit&ajaxrequest=1',function(data, status){
$("#measure_quantity").before(data);
});
});
But then again, I have another question... if the modal window has already been populated with the form, direct bound method should work fine right? still kind of cloudy on what direct and delegated bound means.. and what the difference between the two is,

.click function with an Ajax post

So I got a select menu and when an user select an option, it calls a post function via ajax that generates some table rows via PHP and then it returns the html coding for it. In it, there is an Add button.
What I am trying to do is that when the user clicks the add button, a form shows up.
But for some reason, it is not working...
Here is the code:
$(document).ready(function () {
$(".add_form").hide();
$("#console").change(function () {
var id = $(this).val();
var dataString = 'console_id=' + id;
$.ajax({
type: "POST",
url: "generate-games-list",
data: dataString,
cache: false,
success: function (html) {
$("#games_table_body").html(html);
}
});
});
$(".add_button").click(function () {
alert("HELLO");
var id = this.id;
$.post('manage_games', 'game_id=' + id, function (response) {
alert(response);
});
$("#game_id").val(id);
$(".add_form").show();
});
});
Here is the PHP code that returns the table rows:
$console = Console::find(Input::get('console_id'));
$type = GameType::find(Input::get('type_id'));
if(!Input::has('console_id'))
return "Error";
else{
foreach($console->games()->get() as $console_game){
$available_consoles_string = "";
$game_types_string = "";
//Get all the consoles the game can be played on
foreach($console_game->consoles()->orderBy('name', 'asc')->get() as $available_consoles){
$available_consoles_string = $available_consoles_string . " " .$available_consoles->name .", ";
}
//Get all the types that the game falls in
foreach($console_game->types()->orderBy('type', 'asc')->get() as $game_types){
$game_types_string = $game_types_string . " " .$game_types->type .", ";
}
return "<tr><td>" .$console_game->name. "</td><td>". $available_consoles_string. "</td><td>" .$game_types_string. "</td><td><input type='button' id='" .$console_game->id. "' class='add_button' value='Add'/> / View</td></tr>";
}
}
Any idea why it is not working? When I mean not working, I mean the alert is not showing up but I am not getting any error on the Chrome Console...
Thanks,
Ara
Simply use .on():
$(document).on("click", ".add_button", function(){
// your event code
});
When your js runs a click event is attached to all current elements with the .add_button class. However, you're adding extra buttons via ajax and these won't have trigger the same click event.
To fix this use the code above. It attaches the event to the document so even if you add buttons once the page has loaded the click event will be triggered by them.

Categories