Php called from ajax not working on multiple calls - javascript

I am using a simple javascript function to call a php script when i click a button or link and to return some data. It works fine until i try to call data from a aleady outputed data via that function. Let show you my script:
$(function() {
$(".article_edit").click(function() {
var article_id = $(this).attr("id");
var dataString = 'article_id='+article_id;
//$('a#'+article_id).removeClass('liked');
$('#post-body-'+article_id).fadeOut("slow").html('<img src="images/loader.gif" class="loading" />');
$('a#'+article_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "action/article_enable_edit.php",
data: dataString,
cache: false,
success: function(data){
if (data == 0) {
alert('Actiunea nu a putut fi realizata!');
} else {
$('#post-body-'+article_id).fadeIn("slow").html(data);
}
}
});
return false;
});
});
$(function() {
$(".article_edit_close").click(function() {
var article_id = $(this).attr("id");
var dataString = 'article_id='+article_id;
//$('a#'+article_id).removeClass('liked');
$('#post-body-'+article_id).fadeOut("slow").html('<img src="images/loader.gif" class="loading" />');
$('a#'+article_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "action/article_show.php",
data: dataString,
cache: false,
success: function(data){
if (data == 0) {
alert('Actiunea nu a putut fi realizata!');
} else {
$('#post-body-'+article_id).fadeIn("slow").html(data);
}
}
});
return false;
});
});
<!-- First button-->
<a class="color-transition article_edit" href="#" id="'.$id.'"><i class="fa fa-pencil-square-o"></i></a>
<!-- When i click it the content will be replaced with another one containing this-->
<!-- output from action/article_enable_edit.php -->
<a class="color-transition article_edit_save" href="#" id="'.$id.'" ><i class="fa fa-save"></i></a>
<a class="color-transition article_edit_close" href="#" id="'.$id.'" ><i class="fa fa-ban"></i></a>
<!-- Now, if i click on any link, for example: .article_edit_close, the function will not work. -->
<!-- i should have an output from action/article_show.php -->
<!-- If i put these oow links on the index.php page, they worked, but that is not what i need.-->
Why i can't call a function from a content wich is called by another function? They do not happen at the same time....

You need to bind the click event of link/button using .on for dynamic elements.
So your click event code will look something like this,
$('body').on('click','.article_edit_close',function(e){
// Your code goes here...
});
.on() attach an event handler function for one or more events to the selected elements.

Try using
$(document).on("click",".article_edit",function(){ /* ... */ });
instead of
$(".article_edit").click();

Related

JQUERY: Accessing element cousin by class

Hi I have the following html code:
<li class="grey">
<div class="row">
<button id="test" style="width:50%;" class="btn btn-blue-white cartBtn">Add to Cart</button>
</div>
<div class="row">
Go To Checkout
</div>
</li>
When I load the page, I hide the checkout link button until the user clicks "add to cart". After they click add to cart my javascript looks like this:
$('.cartBtn').click(function () {
//do stuff for preprocessing
var url = "../Store/AddToCart";
$.ajax({
type: "GET",
url: url,
data: {
//add data
},
dataType: "json",
success: function (data) {
if (data.success == true) {
$(this).closest('li').find('.checkoutLink').show();
}
}
});
});
the link never shows back up. I have also tried using
$(this).parent().parent().find('.checkoutLink').show()
as well and had no luck. How do i use jquery to get this anchor tag and make it visible.
The problem is this, when called from within the success function it no longer refers to the outer this. Create a variable outside of Ajax that refers to the original this.
$('.cartBtn').click(function () {
var $this = $(this);
//do stuff for preprocessing
var url = "../Store/AddToCart";
$.ajax({
type: "GET",
url: url,
data: {
//add data
},
dataType: "json",
success: function (data) {
if (data.success == true) {
$this.closest('li').find('.checkoutLink').show();
}
}
});
});

Changing data-tooltip with AJAX isn't working

I have a button in my html template:
<a class="tooltipped" id="stash_recipe_tooltip" data-position="bottom" data-delay="50"
data-tooltip="{{ stash_tooltip }}">
<div id="stash_recipe_btn" class="detail_footer_btn btn-floating col2 center"> + </div>
</a>
later, in the html file, I have:
<script>
function add_recipe_to_stash() {
var stash_plus_or_minus = document.getElementById("stash_recipe_btn").innerHTML
$.ajax({
url: '/ajax/add_recipe_to_stash/',
type: 'GET',
data: {
# this goes to a django view that, in essence, returns a new 'stash_tooltip' var and 'stash_plus_or_minus' var
'stash_plus_or_minus': stash_plus_or_minus,
},
dataType: 'json',
success: function (data) {
document.getElementById("stash_recipe_btn").innerHTML = data.stash_plus_or_minus;
$("#stash_recipe_tooltip").attr('data-tooltip', data.stash_tooltip);
}
});
}
function addClickHandlers() {
$("#stash_recipe_btn").click( add_recipe_to_stash );
}
</script>
It seems like
$("#stash_recipe_tooltip").attr('data-tooltip', data.stash_tooltip);
should be changing my tooltip, but nothing happens. Any idea how to successfully update the data-tooltip without refreshing the page? I've tried different variations of the above line but I can't get it to update.
You can use the tooltip function for that:
success: function (data) {
document.getElementById("stash_recipe_btn").innerHTML = data.stash_plus_or_minus;
$("#stash_recipe_tooltip").tooltip('tooltip', data.stash_tooltip);
}
Try this:
$('#someElement').prop('tooltipText', 'new title');

PHP foreach loop and one AJAX call for each of the loop

This question has already been asked here, but I could see any of the answers working for me.
I have the following code in Laravel 4:
<ul class="list-group">
#foreach($inboxMsg as $inbox)
<li class="list-group-item no-border">
<a href="#{{ $inbox->mid }}" id="fragment1g">
<span class="no-margin sender center-block"><b>John Doe</b>
<small class="pull-right datestamp"><strong>2:00AM</strong></small>
</span>
<span>
<strong>{{ $inbox->subject }}</strong> <i class="fa fa-paperclip att"> 3</i>
</span>
</a>
</li>
#endforeach
</ul>
As you can see I am passing the ID of each message in the URL with # to prevent page reload and in my AJAX I tried to get the value after # (hash). Here is my AJAX
<script type="text/javascript">
$(document).ready(function(){
$('.list-group-item a').click(function (event) {
//Check if the URL has value after hash
if(window.location.hash) {
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
//show loader
$('#loader').fadeIn("slow");
//Proccess data through Ajax
$.ajax({
type: "POST",
url: "{{ URL::route('post-read') }}",
data: { mid : hash_value },
cache: false,
dataTye: "json",
success: function(data)
{
$('#loader').fadeOut("slow");
alert(data["body"]);
}
});;
}
});
})
</script>
With this code it is working but not correctly. It forces me to click twice before alerting the body of the message, and when I click the second message it first brings the body of the first message, until I click it again before I could see the body of second message. But without this line of Jquery "$('.list-group-item a').click(function (event){" the ID is passed in the URL after # (hash) but AJAX call does not work.
Is there any other way to do this?
use event.preventDefault(); to prevent page reload after clicking on link
you can directly take $inbox->mid using attribute using some data attribute
<a data-id="{{ $inbox->mid }}" id="fragment1g">
<span class="no-margin sender center-block"><b>John Doe</b>
<small class="pull-right datestamp"><strong>2:00AM</strong>
</small>
</span>
<span>
<strong>{{ $inbox->subject }}</strong> <i class="fa fa-paperclip att"> 3</i>
</span>
</a>
<script type="text/javascript">
$(document).ready(function(){
$('.list-group-item a').click(function (event) {
event.preventDefault();
var hash_value = $(this).attr("data-id");
//show loader
$('#loader').fadeIn("slow");
//Proccess data through Ajax
$.ajax({
type: "POST",
url: "{{ URL::route('post-read') }}",
data: { mid : hash_value },
cache: false,
dataTye: "json",
success: function(data)
{
$('#loader').fadeOut("slow");
alert(data["body"]);
}
});
});
})
</script>
Dont use the window.location.hash. You sholud put the right url in the element and use event.preventDefault();
PHP:
<a href="{{ URL::route('post-read', array('mid'=>$inbox->mid)) }}">
JS:
event.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('href'),
cache: false,
dataTye: "json",
success: function(data)
{
$('#loader').fadeOut("slow");
alert(data["body"]);
}
});;

How can update and refresh every single row in a ajax loaded div?

I am facing difficulties to update and automatically refresh my table row using jQuery in a AJAX loaded div.
Code to load data in a div after select a value from select option: AJAX part
<script type="text/javascript">
function showUser2(str)
{
<!-- code -->
}
</script>
Select option part:
<select name ='country_select' onchange='showUser2(this.value)'>
<!-- options -->
</select>
Loaded DIV with list of all users for selected country:
<div id='txtHint'></div>
DIV contains:
Header:
User Name Delete User Change Status
Data:
Ben Delete icon Status icon
Max Delete icon Status icon
Code:
<div id="otherdiv">
<!-- Delete/ Enable user -->
<ul>
<li>
<?php echo $data[user_name]; ?>
</li>
<li>
X
</li>
<li>
<a href="#" id="<?php echo $data[training_id]; ?>" class="deassign_training">
<img src='images/on.png' style='border:0;'/>
</a>
</li>
</ul>
<!-- Delete/Disable user -->
<ul>
<li>
<?php echo $data[user_name]; ?>
</li>
<li>
X
</li>
<li>
<a href="#" id="<?php echo $data[training_id]; ?>" class="assign_training">
<img src='images/off.png' style='border:0;'/>
</a>
</li>
</ul>
when I click on image icon to delete/enable/disable user then it didn't work. Here is the code for delete user:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$(".delete_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "deleteajax.php",
data: dataString,
cache: false,
success: function(data)
{
$("#otherdiv").load("index.php");
}
});
return false;
});
});
</script>
Following code for enable/disable user:
$(function()
{
$(".assign_training").click(function()
{
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax(
{
type: "POST",
url: "assign.php",
data: dataString,
cache: false,
success: function(data)
{
$("#otherdiv").load("index.php");
}
});
return false;
});
$(".deassign_training").click(function()
{
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax(
{
type: "POST",
url: "deassign.php",
data: dataString,
cache: false,
success: function(data)
{
$("#otherdiv").load("index.php");
}
});
return false;
});
});
I am not sure why its working after select a country name. I already tried so many techniques from Stack Overflow and other so many website but finally its not working. Its working only if user details loaded directly on the page.
I hope I will found a helpful answer.
Thanks
As far as I see you are initiating delete/enable/disable events before DOM creation.
Try to change these blocks:
<script language="javascript" type="text/javascript">
$(function() {
<!-- YOUR CODE HERE -->
});
</script>
to:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
<!-- YOUR CODE HERE -->
});
</script>
This should help

jQuery - clicking on one element triggers another

i have this jQuery file, but the vote_up click handler keeps conflicting with the vote_down click handler, when i click the vote_down element it changes the vote_up element:
jQuery script:
$(document).ready(function () {
$("a.vote_up").click(function () {
//get the id
var the_id = this.id.split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
$("span.vote_count#" + the_id).html(msg).fadeIn();
$("#" + the_id + " img").attr("src", "img/uparrowActive.png");
}
});
});
});
$(document).ready(function () {
// the vote down function
$("a.vote_down").click(function () {
//get the id
var vote_id = this.id.split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_down&id=" + vote_id,
url: "ajax/votes.php",
success: function (msg) {
$("span.vote_count#" + vote_id).html(msg).fadeIn();
$("#" + vote_id + " img").attr("src", "img/downarrowActive.png");
}
});
});
});
html:
<img src="img/uparrow.png" />
<img src="img/downarrow.png" />
the jQuery and ajax request is wokring fine, but the change of src is the problem, because when i click vote down, it changes the vote_up image!!
You can't use the same "id" value for two different elements.
If you're looking for some sort of strategy for focusing events to a repeating piece of data, utilizing IDs with the number appended to reference the various elements may work, but may not be the best approach.
I assume each repeating item has its own container that repeats. You may be better off placing a unique ID on that container, and finding the elements from there.
Take this for example:
<div id='outerContainer'>
<div id='set_123' class='someContainer'>
<a href='#' class='vote_up'><img src="img/uparrow.png" /></a>
<span class='vote_count'></span>
<a href='#' class='vote_down'><img src="img/downarrow.png" /></a>
</div>
<div id='set_124' class='someContainer'>
<a href='#' class='vote_up'><img src="img/uparrow.png" /></a>
<span class='vote_count'></span>
<a href='#' class='vote_down'><img src="img/downarrow.png" /></a>
</div>
<div id='set_125' class='someContainer'>
<a href='#' class='vote_up'><img src="img/uparrow.png" /></a>
<span class='vote_count'></span>
<a href='#' class='vote_down'><img src="img/downarrow.png" /></a>
</div>
</div>
You could use .delegate() to place click handlers on the #outerContainer that fire when you click the appropriate up/down elements.
Something like:
$(document).ready(function() {
$('#outerContainer').delegate('.vote_up', 'click', function() {
//get the id
var the_id = $(this).closest('.someContainer').attr('id').split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
// Make sure "this" in the callback refers to the element clicked
context: this,
data: "action=vote_up&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
// Not sure where your vote_count is. See the HTML for my placement
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/uparrowActive.png");
}
});
});
$('#outerContainer').delegate('.vote_down', 'click', function() {
//get the id
var the_id = $(this).closest('.someContainer').attr('id').split('_').pop();
//the main ajax request
$.ajax({
type: "POST",
// Make sure "this" in the callback refers to the element clicked
context: this,
data: "action=vote_down&id=" + the_id,
url: "ajax/votes.php",
success: function (msg) {
// Not sure where your vote_count is. See the HTML for my placement
$(this).siblings("span.vote_count").html(msg).fadeIn();
// get the child <img> and set its src
$(this).children("img").attr("src", "img/downarrowActive.png");
}
});
});
});
So the ID with the number you need is on each .someContainer. You traverse up to that container to get the ID, and do your .split().pop().
Then in the AJAX request, I set the context: property for $.ajax() so that this will still refer to the element that was clicked in your callback.
Inside the callback, you find the .siblings() that have the class .vote_count, and set its .html() content.
Finally you use .children() to get the img element, and set its src attribute.
This should give the general idea. You'll need to adjust for your HTML.

Categories

Resources