AJAXing of a form field generated via another AJAX - php

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,

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()

How to send jquery post request using button

I am trying to send post request using jquery. This is the request i am trying to send
$.post("https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", {
key: "1234567891011121314151617181920",
tradeofferid: "$offerid"
}).done(function(data) {
alert("Data Loaded: " + data);
});
Inside my php i have $offerid , and key is always the same .
I want to send it on button click so i created button inside my php
$offerid = $value2['tradeofferid'];
echo '<button id="cancel-offer"> Cancel offer </button>';
how i can connect button with jquery request and send $offerid to the request ?
You just need to select the button by its id attribute, then add a click handler:
$('#cancel-offer').click(function() {
$.post("https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", {
key: "1234567891011121314151617181920",
tradeofferid: "<?= $offerid ?>"
}).done(function(data) {
alert("Data Loaded: " + data);
});
});
I would suggest you have a quick read through the jQuery documentation. It makes a great reference, and also gives you an idea of what jQuery is and is not capable of.
Modify your code like this:
php:
echo '<button id="cancel-offer" data-id="'.$offerid.'"> Cancel offer </button>';
js:
$('#cancel-offer').click(function(){
$.post( "https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", { key: "1234567891011121314151617181920", tradeofferid: $(this).attr('data-id') },function( data ) {
alert( "Data Loaded: " + data );
});
});

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.

.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.

jquery $(event.target).closest('td') getting 'lost' when calling same function more than once at the same time

I am having a problem with the below code and I am not sure of the cause.
Scenario summary:
Basically I have a page with several input fields for inline editing, whenever each one is filled, on blur or pressing enter, a javascript function is called which does the following:
shows "loading" instead of the input field
does an AJAX request to a PHP file
on completion, then replaces the 'loading' with the user's value
Problem:
The above is working perfectly fine if the user edits 1 input field at a time, but when the user edits a 2nd field while the first one is still 'loading', the javascript gets 'lost' and when the 1st AJAX request completes, the "loading" is still always there, but on the 2nd one it is correctly replaced.
Below is the javascript code, I believe the JS confusion is related to "nearestTd", it is as if jquery is 'forgetting' the old nearestTd (from the first call), and only 'remembers' the new one...any suggestions please ?
function action_addSystemCountryLanguageField (event) {
value = $(event.target).val();
nearestTd = $(event.target).closest('td');
var loading=nearestTd.html("<div align='center'><img src='images/loading-small.gif' width='15' height='15' /></div>");
$.ajax({
url: 'actions/pause.php',
type: 'POST',
dataType: 'json',
success: function(response, textStatus, XMLHttpRequest) {
nearestTd.html("<span class='editSystemCountryLanguage'>ok</span>");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (typeof console != 'undefined')
console.dir(XMLHttpRequest);
return false;
}
});
}
PHP code, just a simple pause function so I can have an AJX delay & test this bug:
<?php
sleep(1.5);
?>
the code on the page & the jquery 'listener':
$(".addSystemCountryLanguage").live('blur', action_addSystemCountryLanguageField);
$(".addSystemCountryLanguage").keypress(function(e) {
if(e.keyCode == 13) {
action_addSystemCountryLanguageField(e);
}
});
HTML:
<input class='addSystemCountryLanguage' style='width:80px; border: 0;' value='' />
You are accidentally using global variables.
function action_addSystemCountryLanguageField (event) {
var value = $(event.target).val();
var nearestTd = $(event.target).closest('td');
var loading=nearestTd.html("<div align='center'><img src='images/loading-small.gif' width='15' height='15' /></div>");
.
.
.
}
http://www.jslint.com/ will sometimes catch problems like this for you as well.

Categories