how to get value outside jquery click function - javascript

I have a on click function to get the id of a,and I want to alert it.
The following code is not working showing null, why? thanks
var projectId=null;
$('body').on('click', '#list a', function(){
projectId=this.id; //id should = 30
alert(projectId); //here display 30
});
alert(projectId); //here display null
what i really want to do is :
a.js I have sth like, when I click "a" it redirect to another page which need to render by my projectId:href='/projectDetail' this page call b.js
$.ajax({
type: "GET",
url: 'http://xxx',
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data);
var projectList="<ul style='list-style:none;'>"
for (var i = 0; i < data.data.length; i++) {
projectList += "<li><div id='listall'><a
id='"+data.data[i].projectId+"'
href='/projectDetail'>"+
"<img class='back' src='/img/Homepage_ProjectFrame.png'></li>"
}
var projectList="<ul>"
});
var projectId=null;
$(document).on('click', '#listall a', function (){
event.preventDefault();
projectId=this.id;
alert(projectId);
});
alert(projectId);
b.js I have:
$.ajax({
type: "GET",
url: 'http://xxx?projectId='+projectId
dataType:'json',
contentType:"application/json",
success:function(data){
console.log(data.data);
$(".photoprojectD").attr("src",data.data.projectPhotoUrl);
$(".dlocation p").html(data.data.countryName);
$(".dcategory p").html(data.data.categoryName);
});
So i need projectId from a.js to render dynamic information
Do you have any good ideas?
Thanks a lot for your guys helping

the second alert(projectId); outside the "click" event handler runs as soon as the page loads. Inevitably this is before your "click" handler can possibly be executed, because the user has likely not had time to click on it, and even if they had time, there's no guarantee that they will. Therefore the variable projectId is not populated when that code executes.
You can certainly use projectId outside your "click" event, but you have to wait until after at least one "click" event has happened before you can expect it to have a value.
There's also danger that your hyperlinks are causing the page to postback before any of this ever happens. Since you're using jQuery you can prevent this very easily:
$('body').on('click', '#list a', function(event) {
event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
projectId=this.id; //id should = 30
alert(projectId); //here display 30
});
Lastly, ensure that this other place you want to use the value is not doing anything silly like declaring another "projectId" variable with narrower scope and then trying to use that. For example, this will not work as you wish:
var projectId = null;
$('body').on('click', '#list a', function(event) {
event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
projectId=this.id; //id should = 30
alert(projectId); //here display 30
exampleFunc(); //call the function below
});
function exampleFunc() {
var projectId = null; //oops, another "projectId" with narrower scope (within this function) will take precedence here
alert(projectId); //will be null
});
Whereas this will:
var projectId = null;
$('body').on('click', '#list a', function(event) {
event.preventDefault(); //prevent default hyperlink redirect/reload behaviour
projectId=this.id; //id should = 30
alert(projectId); //here display 30
exampleFunc(); //call the function below
});
function exampleFunc() {
alert(projectId); //will be 30
}

Related

jQuery: Updating global var and re-running function

I have a function that has another function nested that binds a click event to re-run that function with a different ajax URL:
function getInternal() {
var callUrl = 'https://url.com'; // URL ON LOAD
$.ajax({
dataType: "json",
url: callUrl,
success: function(data) {
var obj = data;
$( document ).ready(function(callUrl) {
$( "a.dept" ).click(function() {
var filterDept = $(this).attr('id');
callUrl = 'https://url.com/' + filterDept; // URL TO UPDATE
getInternal(callUrl); // RUN THIS FUNCTION AGAIN
});
});
Unfortunately the click event continues to return the same data. It doesn't look like callUrl is updating.
How do I update a global variable from within a function to re-run itself?
The first line of your function sets your variable to a specific value: var callUrl = 'https://url.com'; Thus, every single time you run this function, the variable will be set to 'https://url.com'.
By moving your variable outside of the function it will become a global variable, and the portion of your code that updates callUrl will persist.
That being said, your code is all sorts of mixed up. You have $( document ).ready() within an AJAX callback, a click event that gets redefined within that with each call, nothing seems to be closed, and you've supplied a parameter for getInternal(); despite the fact that it takes none.
Is something like this what you're after?
$(document).ready(function() {
//On click of link, run AJAX call to changing URL (based on clicked link's ID)
$( "a.dept" ).click(function() {
var filterDept = $(this).attr('id');
var callUrl = 'https://url.com/' + filterDept;
getInternal(callUrl);
});
});
function getInternal(callUrl) {
$.ajax({
dataType: "json",
url: callUrl,
success: function(data) {
alert("Call made to " + callUrl);
}
});
}

AJAX jQuery on click dynamically created only works first time

I am trying to create a dropdown menu that I dynamically insert into using jQuery. The objects I'm inserting are notifications, so I want to be able to mark them as read when I click them.
I have an AJAX call that refreshes the notifications every second from the Django backend.
Once it's been refreshed, I insert the notifications into the menu.
I keep an array of the notifications so that I don't create duplicate elements. I insert the elements by using .append(), then I use the .on() method to add a click event to the <li> element.
Once the click event is initiated, I call a function to .remove() the element and make an AJAX call to Django to mark the notification as read.
Now my problem:
The first AJAX call to mark a notification as read always works. But any call after that does not until I refresh the page. I keep a slug value to identify the different notifications.
Every call I make before the refresh uses the first slug value. I can't figure out why the slug value is tied to the first element I mark as read.
Also, if anyone has a better idea on how to approach this, please share.
Here's my code:
var seen = [];
function removeNotification(elem, urlDelete) {
elem.remove();
console.log("element removed");
$.ajax({
url: urlDelete,
type: 'get',
success: function(data) {
console.log("marked as read");
},
failure: function(data) {
console.log('failure to mark as read');
}
});
}
function insertNotifications(data) {
for (var i = 0; i < data.unread_list.length; i++) {
var slug = data.unread_list[i].slug
var urlDelete = data.unread_list[i].url_delete;
if (seen.indexOf(slug) === -1) {
var elem = $('#live-notify-list').append("<li id='notification" +
i + "' > " + data.unread_list[i].description + " </li>");
var parent = $('#notification' + i).wrap("<a href='#'></a>").parent();
seen.push(slug);
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
}
}
}
function refreshNotifications() {
$.ajax({
url: "{% url 'notifications:live_unread_notification_list' %}",
type: 'get',
success: function(data) {
console.log("success");
insertNotifications(data);
},
failure: function(data) {
console.log('failure');
}
});
}
setInterval(refreshNotifications, 1000);
I really don't know what do you mean with parent[0] in
removeNotification(parent[0], urlDelete);
I think you can simply try $(this)
removeNotification($(this), urlDelete);
but to be honest I find to put
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
inside a loop .. its bad thing try to put it outside a function and use it like
$( document ).ready(function() {
setInterval(refreshNotifications, 1000);
$( document ).on("click", "[id^='notification']", function() {
console.log("onclick " + slug);
removeNotification($(this), urlDelete);
});
});
and try to find a way to pass a urlDelete which I think it will be just one url

Jquery addClass -- Function for New Class

I have a issue in my js file.
This is my Js Code.
<script type="text/javascript">
$(document).ready(function()
{
$(".abc").click(function()
{
$(this).addClass('testingClass');
});
$(".testingClass").click(function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
});
</script>
My HTML :
<button class="abc">Demo</button>
When i load this page in Browser, The addClass function is successfully executing and adding new class named "testingClass".
But When Try to click again t that button (meens : class="testingClass") the alert function does not working. What is the error.
Is JS is not supporting frequent execution of an element ?
Anybody Please help me.
Steps..
One Button has class named abc
When click on it an ajax function will storing current time in database.(ajax function not in stack-code).
after successful ajax response the button class changed to testingClass.
now the class name of the button is testingClass
After some time Click on the Button again (class named:testingClass), i want to call a ajax function with current time of click and store the values in database.
Then the Button class name will changed to old ( abc).
You need to event delegation for dynamic added element
$(document).on("click",".testingClass",function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
Event delegation
Update
For the changed question, you are looking for something like this.
Here is a demo.
$('body').on('click', '.abc', function () {
// event attached to .abc
// updateTime is a method that takes context (this), current timestamp and a function
// we need to send the context so that we have access to the current
element inside the below function which is executed outside the scope
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('testingClass').removeClass('abc');
$('#log').append('Time: ' + data + 'from abc <br/>');
});
}).on('click', '.testingClass', function () {
// event attached to .abc
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('abc').removeClass('testingClass');
$('#log').append('Time: ' + data + ' from testingclass <br/>');
});
});
function updateTime(currentTime, successCallback) {
$.ajax({
context: this, // the context sent from the above methods is used here
url: '/echo/html/',
data: {
html: currentTime
},
method: 'post',
success: successCallback
});
}
Using .one() will help you attach event only once upon multiple clicks.
This handler is executed at most once per element per event type.
I think this is what you are looking for. Adding a handler after the class is added.
$(".abc").click(function(){
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
$(document).ready(function() {
$(".abc").click(function() {
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="abc">Demo</button>

jquery onclick runs twice

I have the following javascript when my script is loaded:
var current_selected_note = $('#new_note');
current_selected_note.addClass('hover active');
$('#note-item-lists').on('click', '.list-group-item', function () {
//removes the hover color from the previous selected
current_selected_note.removeClass('hover active');
// sets the currently selected equal to the selected note
current_selected_note = $(this);
// adds the hover active to the currently selected
current_selected_note.addClass('hover active');
//adds the title of the currently selected to the title input field
$('#txt_new_note_title').val($(this).find('Strong').text());
selected_note_id = $(this).get(0).id;
getNote(selected_note_id);
load_comments(selected_note_id);
});
$( "#note-item-lists").find('li').first().trigger( "click" );
Now AFTER this is loaded i click one of my buttons which has the following javascript:
$('#note-item-lists').on('click','.close',function(){
var r = confirm('Are you sure you wish to delete "'+$(this).next('div').find('.new_note_title').text()+'" ?')
if(r == true){
deleteNote($(this));
$( "#note-item-lists").find('li').first().click();
}
})
function deleteNote(button){
var id = button.closest('li').get(0).id;
$.ajax({
type: 'POST',
url: '/solo/ajax_delete',
dataType: 'json',
data: {
id: id
},
success: function (data) {
}
});
button.closest('li').remove();
}
When this happens (i debug it) and the event function is called first 1 time (adding the class correctly) but is then happens immediatly again.
Anyone tried this before?
Try this, It will call one time.
$('#note-item-lists .close').on('click',function(){
alert("Hello");
});
Try using .off()
$('#note-item-lists').on('click', '.list-group-item', function () {
$(this).off(); //add this here

AJAX call reload only works once

I am New to AJAX and have already asked a few question son this matter, but i have another, I use an AJAX call to auto save a value from a drop down list to database, this works great, however every time i change a value (Their are multiple drop downs with several values each can hold) I want the div to update to reflect the change in value. The AJAX I have is as follows:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).prop('id');
$.ajax({
type: "POST",
url: "saveStatus.php",
data: { statusType : statusVal, jobID: job_id },
success: function(data) {
$('#div1').load('jobs.php #div1', function() {});
}
})
});
});
</script>
So when I change a value in one drop down box (In div1) it refreshs the value, but if i was to change another value in the same or different drop down it no longer refreshs the div or saves the value to my DB, without the reload bit in my AJAX i can change the value in multple fields and it saves, but with the reload part it only happens once
-----EDIT-----
Ok further questioning, I have used
$('#div1').on( 'change', 'select', function( ) {
var statusVal = $(this).val();
var job_id = $(this).prop('id');
$.ajax({
type: "POST",
url: "saveStatus.php",
data: { statusType : statusVal, jobID: job_id },
success: function(data) {
$('#div1').load('jobs.php #div1', function() {});
}
})
});
});
and that works great even for multiple select changes. However what if I have a few selects in a few divs, EG div1, div2 and div3. How can I adapt this code to be able to refresh all divs on a change in any of the divs, or is a case of just having the code 3 times adapted for each div.
-----EDIT-----
Thankyou all, I am able to do this with
$('#div1, #div2').on( 'change', 'select', function( ) { //stuff
Ian
Your listener is bound to the select element, which I'm betting is being blown away and relaced with the load(). Check out event delegation. jQuery makes it easy. Try binding the listener on '#div1'
$('#div1').on( 'change', 'select', function( e ) { //stuff
It should then apply to the refreshed content as well.

Categories