Ajax - prevent click on a successful ajax request - ajax

I have a video thumbnail on my page, with a little icon "Thumbs Down". When you click on that, another thumbnail shows, replacing the other. User can do that as much as they want.
My code is now working only the first time. HTML:
AJAX:
$('.dislike_black').click(function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
When I click the icon the first time, its all fine, triggers the alert, the second time thought, no alert, and the browser is loading the href link.
I tried .preventDefault(); on the success and the complete event, but its not working.
Any hint on how to do this?

Your content is dynamically created so, depending on the version of jQuery you are using, you need the jQuery.live() or jQuery.on() method
jQuery.live() since jQuery 1.3 an event handler for all elements which match the current selector, now and in the future.
jQuery.on() since jQuery 1.7 - Attach an event handler function for one or more events to the selected elements.
Sample
jQuery.live()
$('.dislike_black').live("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
jQuery.on()
$('.dislike_black').on("click", function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
More Information
jQuery.live()
jQuery.on()

Because you are replacing the dom which contains the anchor itself by new html in the ajax success handler. In this case you should use on which will attach event handler to parent or document element whatever you pass as the root element but will trigger the event only on the matching selector which you pass as the second argument. Try this.
$(document).on('click', '.dislike_black', function(e) {
e.preventDefault();
alert("test");
var $aTag = $(this);
$.ajax({
url: $aTag.attr('href'),
type: "POST",
data: {
"sort": $aTag.data('sort'),
"page": $aTag.data('page')
},
success: function(response) {
$aTag.parents("li").replaceWith(response);
}
});
});
.on() reference: http://api.jquery.com/on/ (Ver. 1.7+)
If you are using older version of jQuery you can still achieve this using delegate method whose syntax is same as on but just the first 2 arguments are interchanged.
$(document).delegate('.dislike_black', 'click', function(e) {
//Your code here
});
.delegate() reference: http://api.jquery.com/delegate/

try
$(document).delegate('.dislike_black',"click",function(e) {

Try using event delegation.
// older jquery, use this line:
// $( ".dislike_black" ).live( "click", function ( e ) {
$( document ).on( "click", ".dislike_black", function ( e ) {
e.preventDefault();
alert( "test" );
var $aTag = $( this );
$.ajax( {
url : $aTag.attr( 'href' ),
type : "POST",
data : {
"sort" : $aTag.data( 'sort' ),
"page" : $aTag.data( 'page' )
},
success: function ( response ) {
$aTag.parents( "li" ).replaceWith( response );
}
});
});

Related

How to use JSON result from autocomplete as variable for another autocomplete

I would like to ask You for help mi to figure it out, how to use result of first Complete which is giving me a client number as #select_client_id in another autocomplete.
At one page, i'm selecting order from autocomplete list:
$( function() {
$( "#select_order" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_order_out: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$('#select_order').val(ui.item.label); // display the selected text
$('#select_order_id').val(ui.item.value); // save selected id to input
$('#select_client_id').val(ui.item.client_id);
return false;
}
});
});
Then there is another input field which is selecting packages for this order, where i`m using a client id, from first autocomplete:
$("#select_package").autocomplete({
source: function( request, response ) {
$.ajax({
url: "data/orderData.php",
type: 'post',
dataType: "json",
data: {
find_client_package_on_storage: request.term, client: client
},
success: function( data ) {
response( data );
console.log(client);
}
});
},
select: function (event, ui) {
$('.select_package').val(ui.item.label);
$('.select_package_id').val(ui.item.value);
return false;
}
});
For now, i've got only one client, so variable is declared by:
<script>
client="1";
</script>
How can i do it properly? :)
Well, it takes a little bit longer than normally, but it wasn't priory to figure it out :)
Answer is very simple :)
In #select_order autocomplete, i've add:
select: function (event, ui) {
$('#select_order').val(ui.item.label);
$('#select_order_id').val(ui.item.value);
$('#select_client_id').val(ui.item.client_id);
client_number=$("#select_client_id").val();
return false;
And at the end of body set a variable declaration:
<script>
let client_number = 0;
</script>
That solved my problem :)

How to call ajax only once

I call function from this code :
<div id="header-button-news" class="header-button-info">
<div class="new">2</div>
</div>
My function is
function showNews()
{
//other js which show block
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
}
How can I make only once ajax call? so when content is loaded and page was not refresed not to load ajax? I tried to do boolean variables but nothing, I suppouse it is because I call everytime function. Please give me an idea how to do.
thank you
When you want to do something on that event.
Identify when you have already loaded your data.
var loaded = false;
function showNews() {
//other js which show block
jQuery("#loader").show();
if(loaded) return;
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function(data) {
jQuery('#top-info-news').html(data);
},
complete: function(){
jQuery('#loader').hide();
},
});
loaded = true;
}
Or use one. when you want to call it once.
jQuery('.showNews').one('click', function() {
// your code
});
"Attach a handler to an event for the elements. The handler is executed at most once per element."
reference
Use the .one() function :
Attach a handler to an event for the elements. The handler is executed at most once per element.
I have added an id attribute to the anchor to allow an easier bind, but you could use $("#header-button-news a").one
$(document).ready(function () {
$('#shownews').one('click', function (evt) {
evt.preventDefault(); // prevent default click action
jQuery("#loader").show();
//ajax which load content to block
jQuery.ajax({
type: "GET",
url: link,
dataType: "html",
success: function (data) {
jQuery('#top-info-news').html(data);
},
complete: function () {
jQuery('#loader').hide();
},
});
});
});
Also used event.preventDefault() to prevent the default action on the anchor from being followed
<div id="header-button-news" class="header-button-info">
<a id="a_news" title="Новости"></a>
<div class="new">2</div>
</div>
In JS:
$(function(){
$('a#a_news').one('click',showNews);
})

jquery autocomplete using mvc3 dropdownlist

I am using ASP.NET MVC3 with EF Code First. I have not worked previously with jQuery. I would like to add autocomplete capability to a dropdownlist that is bound to my model. The dropdownlist stores the ID, and displays the value.
So, how do I wire up the jQuery UI auto complete widget to display the value as the user is typing but store the ID?
I will need multiple auto complete dropdowns in one view too.
I saw this plugin: http://harvesthq.github.com/chosen/ but I am not sure I want to add more "stuff" to my project. Is there a way to do this with jQuery UI?
Update
I just posted a sample project showcasing the jQueryUI autocomplete on a textbox at GitHub
https://github.com/alfalfastrange/jQueryAutocompleteSample
I use it with regular MVC TextBox like
#Html.TextBoxFor(model => model.MainBranch, new {id = "SearchField", #class = "ui-widget TextField_220" })
Here's a clip of my Ajax call
It initially checks its internal cached for the item being searched for, if not found it fires off the Ajax request to my controller action to retrieve matching records
$("#SearchField").autocomplete({
source: function (request, response) {
var term = request.term;
if (term in entityCache) {
response(entityCache[term]);
return;
}
if (entitiesXhr != null) {
entitiesXhr.abort();
}
$.ajax({
url: actionUrl,
data: request,
type: "GET",
contentType: "application/json; charset=utf-8",
timeout: 10000,
dataType: "json",
success: function (data) {
entityCache[term] = term;
response($.map(data, function (item) {
return { label: item.SchoolName, value: item.EntityName, id: item.EntityID, code: item.EntityCode };
}));
}
});
},
minLength: 3,
select: function (event, result) {
var id = result.item.id;
var code = result.item.code;
getEntityXhr(id, code);
}
});
This isn't all the code but you should be able to see here how the cache is search, and then the Ajax call is made, and then what is done with the response. I have a select section so I can do something with the selected value
This is what I did FWIW.
$(document).ready(function () {
$('#CustomerByName').autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
},
});
},
select: function (event, ui) {
$('#CustomerID').val(ui.item.id);
},
minLength: 1
});
});
Works great!
I have seen this issue many times. You can see some of my code that works this out at cascading dropdown loses select items after post
also this link maybe helpful - http://geekswithblogs.net/ranganh/archive/2011/06/14/cascading-dropdownlist-in-asp.net-mvc-3-using-jquery.aspx

jQuery live help

I have the following script which works perfectly until I regenerate the links ".resultLink" via jquery ajax:
$("a.resultLink").live('click', function()
{
var that = this;
$.ajax({
url: 'most_used.aspx',
type: 'POST',
data: { strMostUsedID:$(that).attr("href") },
error: function() { },
success: function() { }
});
});
"live" normally fixes this for me but this time it did not. Not sure what I am doing wrong.
The most likely cause I can think of is the selector not matching, double check that the .resultLink class is being applied to the new links...if it's not the .live() handler won't match the selector.

Get the Selected Item of DropDownList for Ajax Get

I'm trying to initiate an ajax request whenever a person changes the value of a drop down list. I want to send the selected item of the drop down as a query string parameter.
How do I get the selected item from the drop down list using MooTools?
var theUrl = 'http://someurl.com';
window.addEvent( 'domready', function() {
$('ddl').addEvent( 'change',
function(event) {
var parameter = $('ddl').SOMETHING(); // help!
new Request({
url: theUrl,
data: { 'someParameterId' : parameter },
method: 'get',
onComplete: function(data) { alert(data); },
}).send();
}
);
});
Found it!
var parameter = $('ddl').get('value');

Resources