Been scratching my head all night on this issue. Im still learning Jquery and just starting with ajax. I am trying to implement something similar to this https://codeontime.com/print/learn/rest/jquery/crud-create-read-update-delete.
I have a simple edit button in which i stored the ID in in a data-ID attribute. For example below is what my button would look like.
<button class='edit_button btn btn-info btn-circle btn-xs' type='button' value='Edit' data-ID='1'></button>
What im trying to accomplish is to pass the data-ID value into a variable and pass it into my function. Here the listener I put in place to capture the ID and its working fine:
$(document).ready(function () {
$(".edit_button").click(function() {
var Button_ID = $(this).attr("data-ID");
IncidentManager.showIncidentDetails();
});
The problem I have is that I need to pass the button_ID variable onlick to my variable function and dosent seem to be working correctly. I feel like im missing something there.
Below is my full script:
var IncidentManager = {
// Returns the url of the application server of a demo web app.
basePath: function () { return '../../../../_vti_bin/listData.svc'; },
// This function will loadup the data into the modal form,
showIncidentDetails: function (Button_ID) {
if (Button_ID == null) return;
alert(Button_ID);
$.ajax({
url: '../../../../_vti_bin/listData.svc/GDI_Tableau_de_bord('+ID+')',
cache: false,
dataType: 'json',
success: function (data) {
$.each(data, function (index, incident) {
$('#Description').attr('value', incident.Description);
$('#Incident').attr('value', incident.Incident);
$('#état').attr('value', incident.ÉtatValue);
$('#Priorité').attr('value', incident.PrioritéValue);
$('#DateDeDébut').attr('value', incident.DateDeDébut);
$('#DateDeFin').attr('value', incident.DateDeFin);
});
}
});
},
};
$(document).ready(function () {
$(".edit_button").click(function() {
var Button_ID = $(this).attr("data-ID");
IncidentManager.showIncidentDetails();
});
});
Any help is appreciated.
You just pass the variable to the function - programming doesn't work by just having variables named similarly, hence what you want is:
$(document).ready(function () {
$(".edit_button").click(function() {
var Button_ID = $(this).attr("data-ID");
IncidentManager.showIncidentDetails(Button_ID);
});
});
also this bit:
....
url: '../../../../_vti_bin/listData.svc/GDI_Tableau_de_bord('+ID+')',
You probably meant
url: '../../../../_vti_bin/listData.svc/GDI_Tableau_de_bord('+Button_ID+')',
as there is no ID variable in your code.
Incidentally, you can use the jQuery .data function instead of .attr:
var Button_ID = $(this).data("id");
However, note that .data will treat your data attribute as lowercase.
Related
I have a form that has these buttons in footer
<button type="button" class="btn btn-warning redirect store-submit">Add and redirect</button>
<button type="submit" class="btn btn-success store-submit">Just add</button>
Although form is not submitted by these. They are used to trigger jQuery event
$("button").click(function(e){
if($(this).hasClass('store-submit')){
e.preventDefault();
var form_action = $("#add-modal").find("form").attr("action");
var data = $("#add-modal").find("textarea[name='data']").val();
var token = $('meta[name="csrf-token"]').attr('content');
var type = {{$user->type}};
$.ajax({
dataType: 'json',
type:'POST',
url: form_action,
data:{data:data, _token:token}
}).done(function(data){
$("#add-modal").modal('hide');
update(data.id); //calling out another function
if($(this).hasClass('redirect')){ //DOESNT WORK
//some action
}
}).error(function(data){
//error
});
}
});
The weird thing is that first class-check is working. Altough whatever button i click it never triggers part when class "redirect" is checked. I am kinda struggling to resolve this issue and i have no idea what could've I possibly did wrong. Any help would be greately appreciated.
Have a nice day.
Your $(this) is not pointing to the button anymore. In order to fix this, you can use .bind() as suggested by #dfsq or you can assign the $(this) to a variable and then use it. Like
var btn = $(this);
And later use the above as
.done(function(data) {
$("#add-modal").modal('hide');
update(data.id);
if(btn.hasClass('redirect')) {
//some action
}
Also, the good part over here is that you don't have to call $(this) everywhere, as you are holding a reference of $(this) in a variable. So you can also change
if($(this).hasClass('store-submit')) {
TO
if(btn.hasClass('store-submit')) {
//and practically everywhere you can use btn instead of $(this)
You need to bind callback function to correct context. One way to do it is using Function.prototype.bind:
.done(function(data) {
$("#add-modal").modal('hide');
update(data.id); // calling out another function
if ($(this).hasClass('redirect')) {
//some action
}
}.bind(this)) // note: bind(this) call
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);
}
});
}
I am trying to execute a $.ajax() inside a function called by a .on() method, so that in the newlly attached data, it would be possible to execute a script on a .click() event - I know this is probably something similar to other requests, but i have tryed and tryed, and can't find what is wrong withthe code...
The ajax function is called by a change in a select, and 'this' is passed as a variable to the function.
The data is correctly inserted inside the targeted div, but it seems that there is no bubbling, because no javascript runs from it (but runs outside of targeted div).
I used .on() so it would bubble up, and update the DOM, and I dont see wath I am doing wrong with it...
The ajax is called with:
$("body").on("change", "[data-project-ajaxSelect='true']", {select: this},Select_AjaxCall);
function Select_AjaxCall(event) {
$select = event.data.select;
if (typeof $select.data === "undefined" || $select.data === null) {
var $select = $(this);
}
var options = {
url: $select.attr("data-project-action"),
type: $select.attr("data-project-method"),
target: $select.attr("data-target"),
data: { guid: $select.val() }
}
$.ajax({
type: options.type,
url: options.url,
data: options.data,
dataType: "html",
success: function (data) {
console.log(data)
$(options.target).html(data);
}
});
return false;
};
From that code, a button is added with the following View code:
<button id=#Model.Guid
class="button default cycle-button"
data-toggle="modal"
data-target="#modalDiv"
data-backdrop="static"
data-keyboard="true"
data-modal-modal="true"
data-modal-controller="Fin_Movement_Type"
data-modal-action="Create"
data-modal-var-guid=#Model.Guid
data-modal-var-modal=#ViewBag._modal>
<span class="icon mif-plus"></span>
</button>
And by cicking on this button, the following .click() event should be fired...
$("[data-modal-modal='true']").click(function () { ... }
But it isn't.
Please Help me find where is the bug with my code... thank you.
Edit
It seems you need live functionality that has been removed from jQuery, but you can use on instead of that, this way:
$(function () {
$(document).on("click","[data-modal-modal='true']", function () {
alert('clicked');
});
});
Original
You can add your code at the end of your success method:
success: function (data) {
console.log(data);
$(options.target).html(data);
$("[data-modal-modal='true']").on("click", function() {
alert('clicked!');
});
}
Also you can load the button with suitable script in onclick attribute, for example:
<button id="#Model.Guid"
...
onclick="alert('clicked!');">
<span class="icon mif-plus"></span>
</button>
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
Here's my JavaScript:
function privacy(current)
{
var $this = $(current),
$scope = $this.closest('.uk-button-group'),
value = $this.val();
$.ajax({
type: 'post',
url: '/privacy.php',
data: {key: value },
success: function () {
}
});
}
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy($this);
alert('A button has been clicked!');
});
});
And here's my HTML:
<div class="uk-button-group">
<button class="uk-button" id="privacy1" value="1">Public</button>
<button class="uk-button" id="privacy2" value="2">Protected</button>
<button class="uk-button" id="privacy3" value="3">Private</button>
</div>
When I click on one of the buttons, it should call the privacy function and alert me that a button has been clicked but it doesn't. Can anyone help me and show me what's wrong with my code? Much appreciated thank you!
You do not have any identifier $this, you probably need to change $this with $(this) or simply this to pass the event source object
privacy(this);
OR
privacy($(this));
Replace this :-
privacy(this);
Try here: http://jsfiddle.net/pqdgT/
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy($(this));
alert('A button has been clicked!');
});
});
Here is your working code
And here is the refined code
function privacy(current)
{
var btn = $(current),
scope = $(btn).closest('.uk-button-group'),
value = $(btn).val();
$.ajax({
type: 'post',
url: '/privacy.php',
data: {key: value },
success: function () {
}
});
}
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy(this);
alert('A button has been clicked!');
});
});
Please avoid reserved keywords while naming variables - Here is the list of reserved words
And be careful with your syntax and feel free to use the browser console.