Pass Parameter to Selector for Ajax Call onClick? - javascript

Have a JQUERY AJAX call in a $(document).ready(function()..) that loops through MongoDB docs and adds HTML Divs to the page with a .get
Included in each Div is a <button type='button' id='deleteItem' class='close' onClick='deleteThisItem(" + i + ")' aria-hidden='true'>×</button>"
Each Div also has a form field, with a hidden value for returning the doc _id to then use in Express/Node.js to find and delete the correct doc (this does work in another app..)
"..<form name='theForm' id='theForm" + i + "'>
<input type='hidden' name='iD' id='iD' value='" + doc._id + "'>.."
Am looking to have the button delete the MongoDB doc onClick using an AJAX .post
// handle DELETE (x) button clicks
$('#deleteItem').click(function(i) {
number = i;
alert(number);
// make an ajax call
$.ajax({
dataType: 'json',
data: $('#theForm' + number).serialize(),
type: 'POST',
url: "http://localhost:9999/delete",
success: gotAllSuccess,
error: gotAllFailure
});
});
Tried using a global variable (not ideal) var number = 0;, to pass the i parameter through a function outside of the $(document).ready(function()..) and have been researching callback techniques to callback the ajax, but nothing has done the trick..
function deleteThisItem(i)
{
number = i;
alert(number);
//some callback to the Jquery in the ready doc?
}

Since you have multiple records, don't use id for the button since id of an element must be unique, use class attribute to group them. Also there is no need to have an inline click handler
<button type='button' class='close deleteItem' data-id='" + i + "' aria-hidden='true'>×</button>
then use delegated event handler like
jQuery(function ($) {
$(document).on('click', '.deleteItem', function () {
var $this = $(this);
var number = $this.data('id');
alert(number);
// make an ajax call
$.ajax({
dataType: 'json',
data: $('#theForm' + number).serialize(),
type: 'POST',
url: "http://localhost:9999/delete",
success: gotAllSuccess,
error: gotAllFailure
});
});
})

Related

unable to target clicked element on successful Ajax return, when multiple elements have same name

i am trying to target 'clicked' element on successful Ajax return, when multiple elements have same class name.
<td data-name='tom' class="status">click</td>
<td data-name='jack' class="status">click</td>
<td data-name='phil' class="status">click</td>
I am able to target the clicked element using this.i.e:
var name = $(this).attr("data-name");
I am however unclear how to target that same element on successful ajax return.
below is my ajax code example:
$(".status").click(function(event){
event.preventDefault();
var name = $(this).attr("data-name");
$.ajax({
url: FORM_URL,
type: "POST",
data: {name:name},
showLoader: true,
cache: false,
success: function(data){
var el = $(this)('.status');
el.empty();
el.append(
'<div class="status">' +
'<p>name changed</p>' +
'</div>'
)
}
},
});
return false;
});
The 'this' does not work on ajax success
keep element as a variable like so -
statusElement = document.querySelector('.status');
then add event listener and use the variable inside your function -
statusElement.addEventListener('click', function(event) {
statusElement.empty();
})

jQuery AJAX running twice on click

I'm trying to make two Ajax calls in one page using jQuery. The first Ajax runs successfully and produces results. Second Ajax is supposed to fire up on button click and show the result, but it runs twice every time I click on the button. And initially on the first time clicking on the button, I have to click twice before it produces a result. Here's what I'm trying to do:
function showPicture() {
$("button").click(function() {
var id = this.id;
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
});
}
Here's my button:
<button id=" . $count . " onclick=showPicture() value=" . htmlentities($result['Poster']) . ">Click Me!</button>
I have seen similar questions on Google but I cannot figure out what the problem is. Any help would be greatly appreciated.
You have 2 onClick handlers, somewhat:
onClick
$("button").click()
Remove one of the handlers.
Example
function showPicture(id) {
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': $(this).val()},
success: function(data) {
console.log(id);
$("#" + id).replaceWith("<img src=" + data + " />");
}
});
}
<button id=" . $count . " onclick=showPicture(" . $count . ") value=" . htmlentities($result['Poster']) . ">Click Me!</button>
Your function 'showPicture' which you are calling from the html attribute below
<button id=" . $count . " onclick=showPicture()
is calling your function as you would expect.
but the function showPicture() itself is then binding a onclick event
function showPicture() {
$("button").click(function() { <------- this
......
So it is being hit twice as you have the attribute onclick and the even binding onclick.
The event click is on all html buttons.
What you should do: Remove the binding in the function to all buttons
function showPicture(caller) {
var id = $(caller).attr("id");
var val = $(caller).val();
console.log(id);
console.log(val);
$.ajax({
type: 'POST',
url: 'displaySearch.php',
data: {'getTile': val },
success: function(res) {
--you are replacing the button with an image... or something like that
$("#" + id).replaceWith("<img src=" + res+ " />");
}
});
}
html
<button id=".$count." onclick="showPicture(this)" value=".htmlentities($result['Poster']).">Click Me!</button>

Id selector not working for input type submit

I am trying to read a table when I click on total button,the button is created on ajax call with table I tried with both id attribute and input type submit selectors but I am not able to read the button,but when I tried to call javascript function on button click the javascript function is called,can anyone explain this and how should I read using jquery selectors
$.ajax({
type:'POST',
url:'/pos/addproduct',
dataType: "json",
data:JSON.stringify(order),
contentType: "application/json; charset=utf-8",
success:
function(data){
i++;
console.log(i);
$.each(data,function(index,value){
var temp = "qty" + data[index].barcodeid.trim();
var qtyitm=$("#"+temp);
if(qtyitm.length != 0){
qtyitm.html(data[index].qty);
//("#price"+(data[index].barcodeid.trim())).html(data[index].price);
temp = "price" + data[index].barcodeid.trim();
qtyitm = $("#"+temp);
qtyitm.html(data[index].price);
}
else{
var row=$("<tr><td>"+data[index].oid+"</td>"+"<td>"+data[index].pname.trim()+
"</td>"+
"<td id=\"qty"+data[index].barcodeid.trim()+"\">"+data[index].qty+"</td>"+
"<td id=\"price"+data[index].barcodeid.trim()+"\">"+data[index].price+"</td>"+
"<td>"
+data[index].barcodeid.trim()+"</td></tr>"
);
$("#firstrow").after(row).removeClass("hidden");
}
})
if(i==1){
var row1=$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
$("#order tbody").append(row1);
}
}
})
});
$('input[id="calculateTotal"]').click(function(event){
alert("hello");
})
Since the submit button #calculateTotal was added dynamically via js code in :
$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
You should use event delegation on() to attach click event to it, like :
$('body').on('click', 'input[id="calculateTotal"]', function(event){
alert("hello");
})
Hope this helps.
Browser parses your javascript code when your page is loaded and attaches event listeners to DOM elements in your initial loading (in that case your button does not exits as you simply attach it to existing DOM tree [hence no event bound] )
Solution is use $('document').on('event','selector','callback') so with you code :
var row1=$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
$("#order tbody").append(row1);
and in Js:
$('document').on('click','#calculateTotal',function(){
//do your stuff here
});
Hope it helps...:D

jQuery grabbing wrong form when using ajax

I have a php function that loops thru matches in a database, inside the loop, there is a form that gets returned to the page where the function is called:
while($row=mysql_fetch_array($get_unconfirmed))
{
echo "<form name='confirm_appointment' method='post' class='confirm_appointment'>";
echo "<input type='hidden' name='app_id' value='$appointment_id'>";
echo "<input type='hidden' name='clinic_id' value='$clinic_id'>";
echo "<td><input type='submit' class='update_appointment_button' value='$appointment_id'></td>";
echo "</form>";
}
Then I have jQuery to submit the form:
$( document ).ready(function() {
$(".update_appointment_button").click(function(){
var url = "ajax/update_appointment_status.php";
$.ajax({
type: "POST",
url: url,
data: $(".confirm_appointment").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
But the issue is, the way its set up, no matter what row I push "submit" for - I always get the values from the last row (form).
So I know the issue, I am not telling jQuery to get the values from the form with the button thats pushed. I need to somehow use .this maybe, but just cant seem to figure out the correct syntax.
Any help would be appricated!
You can access its parent form like this
data: $(this).closest(".confirm_appointment").serialize(),
or something like this
data: $this.parent().parent().serialize(),
Another way: replace the button click event by the form submit event.
$(document).ready(function () {
$('.confirm_appointment').submit(function (e) {
e.preventDefault();
var url = "ajax/update_appointment_status.php";
var serialized = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: serialized,
success: function (data) {
alert(data); // show response from the php script.
}
});
});
});
JSFiddle demo

Replace javascript onmouseover with jQuery only

I have a page that displays a dynamic amount of "orders" and I have a button to "view" and another button to "print". To display the specific OrderNumber I'm using a javascript function triggered by onmouseover and a jQuery ajax function to change the button text, make a database entry, and then view or print another page. The problem is the order is viewed or printed MULTIPLE times from onmouseover. How can use only jQuery and call the specfic OrderNumber? Here is the code I'm using now:
This code is repeated for each order:
<div class="console_orders_details">
<input type="button" value="View"
id="vieworder'.$row[orderid].'" onmouseover="vieworder('.$row[orderid].');">
</div>
Here is the function to view the order:
function vieworder(id){
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result)
{
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
I'm assuming I need to eliminate the "vieworder" function and use a pure jQuery function. However, I don't know how to send over the order "id", which is why I used javascript.
You can target all elements with an ID that starts with vieworder, and then store the row ID as a data attribute :
<div class="console_orders_details">
<input type="button" value="View" id="vieworder'.$row[orderid].'" data-id="'.$row[orderid].'">
</div>
JS
$(function(){
$('[id^="vieworder"]').on('click', function(){
var orderid = $(this).data('id'),
btn = $('input[type="button"]', this);
$.ajax({
url: "includes/ajax/console-view.php",
dataType: 'html',
data: {orderid : orderid}
}).done(function(result) {
window.open("print.php?view=1&orderid="+orderid+"");
btn.val("Viewed!").fadeIn(400);
});
});
});
Your onmouseover event is probably being fired many times, resulting in your problem. This might help to stop unwanted extra calls, by ignoring them unless the previous one has completed.
var activeRequests = {}; // global
function vieworder(id){
if (activeRequests[id]) { return; }
activeRequests[id] = true;
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
delete activeRequests[id];
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
First, don't have a dynamic id that you have to parse, and don't have an event handler in your html:
<div class="console_orders_details">
<input type="button" value="View" class="vieworder" data-id="$row[orderid]">
</div>
Next, create an event handler for just what you want to do. .one() will set an event handler to fire only once:
$(document).ready(function (){
$(".console_orders_details").one("mouseover", ".vieworder" function(){
var dataString = "orderid=" + $(this).data("id");
$.ajax({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
window.open("print.php?view=1&" + dataString);
$(this).val("Viewed!");
}
});
});
});
If you want this to work onclick, then just change the mouseover to click. Also, fadeIn doesn't work on values. Here is a fiddle that has the basics: http://jsfiddle.net/iGanja/EnK2M/1/

Categories