Targeting specific element jquery - javascript

I have searched this on the net however couldn't find a solution, simply I would like to replace the content inside button element with ajax response. The only problem I am facing is that, the whole divs are being changed not the one I click on. If I change the class to id only the first one changes not the specific button I want. So how do I replace the content of specific button?
PHP Code:
while($row = $result->fetch_assoc()){// there are four rows so I have 4 buttons.
echo "<button class=btn btn-primary test' value='."$row['id']".'>."$row['voteup']".</button>";
}
javascript code:
$(function() {
$('.test').on('click', function() { // attach the click to the button
var test_val = $(this).val(); // Grab the value from the button
$.ajax({
type: "GET",
url: "test.php", // Move ?tar=vrate to the data array.
data: {tar: 'vrate', test: test_val},
cache: false,
success: function(response)
{
$(".test").fadeIn('slow').html(response);//this is replacing all 4 buttons not just one, if I change the class to id, only the first one is being replaced with the response. I also tried $( .test", this) but no luck.
}
});
});
});

$(function () {
$('.test').on('click', function () {
var test_val = $(this).val();
$.ajax({
// -------v Set the context of the callback
context: this,
type: "GET",
url: "test.php",
data: {
tar: 'vrate',
test: test_val
},
cache: false,
success: function (response) {
// v--and use `this` here
$(this).fadeIn('slow').html(response);
}
});
});
});

Try to use the $(this) reference here to achieve what you want,
$('.test').on('click', function() { // attach the click to the button
var test_val = $(this).val(); // Grab the value from the button
var $this = $(this);
$.ajax({
type: "GET",
url: "test.php", // Move ?tar=vrate to the data array.
data: {tar: 'vrate', test: test_val},
cache: false,
success: function(response)
{
$this.fadeIn('slow').html(response);
}
});
});

Related

Add removed element back to DOM jQuery 2

I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/

PHP jQuery HTML - Getting custom HTML attribute

I have a PHP file which puts out all orders in the system and adds the custom attribute oid (order-id) to all the links. My links look like:
<a href='#' class='completeOrder' oid='$order_id'>$status</a>
Which gives correct html, when I do inspect element I get this
<a href='#' class='completeOrder' oid='8'>Un-completed</a>
What I would like to do is when this link is clicked, spawn a form with checkboxes and a submit button with the correct order ID in it's html to send. So I can send the form and the order id to another PHP file for processing ( in this case updating the order status ).
What I am doing to spawn the form with the checkboxes is using a jQuery AJAX call, but when I try to alert the order ID to check if jQuery got the oid correctly it tells me its undefined... :
$("body").delegate(".completeOrder", "click", function(event) {
event.preventDefault();
getCompleteOrderTools();
$(".content").toggleClass("hidden");
$('div.hidden').fadeIn(800).removeClass('hidden');
$("#notifications-drop").toggleClass('hidden');
});
function getCompleteOrderTools() {
var o_id = $(this).attr('oid');
alert(o_id);
$.ajax({
url: "action.php",
method: "POST",
data: {
getCompleteOrderTools: 1,
orderId: o_id
},
success: function(data) {
$(".row").append(data);
},
});
}
Your main issue was that you are referencing this in wrong context as the this available in your function getCompleteOrderTools is different that this that you wanted to refer for the click event of your desired link.
You have 2 options :
either use jQuery(this).attr('oid');
Or
use jquery data attributes
<a href='#' class='completeOrder' data-oid='$order_id'>$status</a>
jQuery(this).data('oid');
So your code with .attr will look like :
$("body").delegate(".completeOrder", "click", function(event) {
event.preventDefault();
var myThis = $(this);//This is the 'this' corresponding to the link clicked
getCompleteOrderTools(myThis);
$(".content").toggleClass("hidden");
$('div.hidden').fadeIn(800).removeClass('hidden');
$("#notifications-drop").toggleClass('hidden');
});
function getCompleteOrderTools(myThis) {
var o_id = myThis.attr('oid');
alert(o_id);
$.ajax({
url: "action.php",
method: "POST",
data: {
getCompleteOrderTools: 1,
orderId: o_id
},
success: function(data) {
$(".row").append(data);
},
});
}
The jQuery object ain't passed to your function. You should do the following:
$("body").delegate(".completeOrder", "click", function(event) {
event.preventDefault();
getCompleteOrderTools(jQuery(this));
$(".content").toggleClass("hidden");
$('div.hidden').fadeIn(800).removeClass('hidden');
$("#notifications-drop").toggleClass('hidden');
});
function getCompleteOrderTools(_this) {
var o_id = _this.attr('oid');
alert(o_id);
$.ajax({
url: "action.php",
method: "POST",
data: {
getCompleteOrderTools: 1,
orderId: o_id
},
success: function(data) {
$(".row").append(data);
},
});
}
By passing jQuery(this) to your function, you now have full access to the jQuery object from your click event.

Hiding the first table when the second table is loaded

I am trying to drill down to detail rows when a user clicks on a cell in table R.So when a cell is clicked Table L is loaded and Table R has to be hidden . I tried to use $('#RegionTable').hide but it hides the table when it is loaded .but i want it to be hidden only on second click
`<script type="text/javascript">
$(document).ready(function($) {
$('#lsearch').click(function(){
makeAjaxRequest();
});
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'php/l_search.php?op=1',
data: {name: $('#l').val()},
type: 'get',
success: function(response) {
$('table#R tbody').html(response);
}
});
}
});
$(document).on('click','#loc_code',function() {
var url = $(this).text();
url = 'php/l_search.php?op=2&l_code='+url ;
$.ajax({
url: url,
type: 'get',
success: function(response) {
$('table#L tbody').html(response);
}
});
return false;
$('#R').toggle("slide", { direction: "right" }, 1000);
});
</script> `
Instead of:
.on('click')
do:
$('#loc_code').dblclick(function(){
https://api.jquery.com/dblclick/
actually I used $("#R").hide(); and it works

Ajax post with on()

$('body').on('click','.removebet i',function(e){
var a = $(this).attr("id");
var data = "a="+a;
$.ajax({
type: "POST",
url: "yorumcikar.php",
data: data,
success: function(e){
});
I'll explain the problem. I can post AJAX form with this function and there's no problem except the .removebet i comes from the ajax.
If I append .removebet i with AJAX this function doesn't work because it doesn't call AJAX.
example:
$(".maindiv").html("<span class='removebet'><i>Yes</i></span>");
Then when I clicked to 'i' tag the function at top doesn't work.
I believe this should work.
$('.removebet > i').click(function(event){
var a = $(this).attr("id");
alert(a);
$.ajax({
type: "POST",
url: "yorumcikar.php",
data: data,
success: function(retval){
alert(retval);
}
});
});
EDIT
This will work, however each newly added item will not be bound as the binding has already happened. In order to get newly added items to be bound as well you will have to rebind them when they are added.
$.ajax({call to get your new item},
success: function(data){
// add to dom
bindElement(newElement);
}
});
function bindElement(element){
$(element).click(function(event){
var a = $(this).attr("id");
alert(a);
$.ajax({
type: "POST",
url: "yorumcikar.php",
data: data,
success: function(retval){
alert(retval);
}
});
});
}

merging two small pieces of jquery codes

Following are two pieces of jquery code. First one prints a text message when clicked on a link, and the second slides down a div when click on a link. I want to merge second code into first one, so that when I click the link, it displays the message (as the first code does), and also slides down the #votebox (as done in second code, and show content in that.
I will be very thankful for any help.
$("a.vote_up").click(function(){
the_id = $(this).attr('id');
$("span#votes_count"+the_id).fadeOut("fast");
$.ajax({
type: "POST",
data: "action=vote_up&id="+$(this).attr("id"),
url: "votes.php",
success: function(msg)
{
$("span#votes_up"+the_id).fadeOut();
$("span#votes_up"+the_id).html(msg);
$("span#votes_up"+the_id).fadeIn();
//Here, I want to slide down the votebox and content div (from code below).
}
});
});
The following code slides down votebox div and displays content in it, I want to include that in the above code.
$("a.vote_up").click(function(){
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
//I want to include this votebox in above code.
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax({
type: "POST",
url: "rating.php",
data: dataString,
cache: false,
success: function(html){
$("#flash").fadeOut("slow");
//and want to use this div as well.
$("#content").html(html);
}
});
});
Thanks for any help.
Simple way is to define a seperate function for voteDown and call it from the success function:
e.g
$("a.vote_up").click(function(){
the_id = $(this).attr('id');
$("span#votes_count"+the_id).fadeOut("fast");
$.ajax({
type: "POST",
data: "action=vote_up&id="+$(this).attr("id"),
url: "votes.php",
success: function(msg)
{
$("span#votes_up"+the_id).fadeOut();
$("span#votes_up"+the_id).html(msg);
$("span#votes_up"+the_id).fadeIn();
var that = this;
voteDown.call(that);
}
});
});
function voteDown()
{
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax({
type: "POST",
url: "rating.php",
data: dataString,
cache: false,
success: function(html){
$("#flash").fadeOut("slow");
//and want to use this div as well.
$("#content").html(html);
}
});
}
Edit: Corrected the JS for Votedown function.

Categories