How to call ajax only once - ajax

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);
})

Related

Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

I have the following code in my MVC controller:
[HttpPost]
public PartialViewResult GetPartialDiv(int id /* drop down value */)
{
PartyInvites.Models.GuestResponse guestResponse = new PartyInvites.Models.GuestResponse();
guestResponse.Name = "this was generated from this ddl id:";
return PartialView("MyPartialView", guestResponse);
}
Then this in my javascript at the top of my view:
$(document).ready(function () {
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});
function SetData(data)
{
$("#divPartialView").html( data ); // HTML DOM replace
}
});
Then finally my html:
<div id="divPartialView">
#Html.Partial("~/Views/MyPartialView.cshtml", Model)
</div>
Essentially when a my dropdown tag (which has a class called SelectedCustomer) has an onchange fired it should fire the post call. Which it does and I can debug into my controller and it even goes back successfully passes back the PartialViewResult but then the success SetData() function doesnt get called and instead I get a 500 internal server error as below on Google CHromes console:
POST http:// localhost:45108/Home/GetPartialDiv/1 500 (Internal Server
Error) jquery-1.9.1.min.js:5 b.ajaxTransport.send
jquery-1.9.1.min.js:5 b.extend.ajax jquery-1.9.1.min.js:5 (anonymous
function) 5:25 b.event.dispatch jquery-1.9.1.min.js:3
b.event.add.v.handle jquery-1.9.1.min.js:3
Any ideas what I'm doing wrong? I've googled this one to death!
this line is not true: url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
$.ajax data attribute is already included route value. So just define url in url attribute. write route value in data attribute.
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: '#Url.Action("GetPartialDiv", "Home")',
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

jsFiddle testing jQuery AJAX request with echo

The following code is alerting 'undefined' and not appending the html from the response data as I expected. Does anyone know why?
JavaScript:
$(function() {
$('.document').on('click', '.ajax', function(e) {
e.preventDefault();
// ajax request
$.ajax({
async: true,
cache: false,
type: 'post',
url: '/echo/html/',
data: {
html: '<p>This is echoed the response in HTML format</p>',
delay: 1
},
dataType: 'html',
beforeSend: function() {
console.log('Fired prior to the request');
},
success: function(data) {
console.log('Fired when the request is successfull');
$('.document').append(data);
},
complete: function() {
console.log('Fired when the request is complete');
}
});
});
});​
HTML:
<div class="document">
<a class="ajax" href="#">Fire an AJAX request</a>
</div>​
Example jsFiddle: http://jsfiddle.net/L6bJ2/3/
The HTTP method is specified with by type rather than method, so you should be using;
type: 'post',
Because you've specified the response type as HTML, you get a String passed in the data parameter of the success callback; but it looks like you're expecting JSON as you're trying to use data.html. Instead, use data directly;
success: function(data) {
console.log('Fired when the request is successfull');
$('.document').append(data);
},
With these changes, you'll find it works: http://jsfiddle.net/L6bJ2/6/
Live Example is here
https://stackoverflow.com/a/34940340/5361795
use beforeSend or complete callback functions in ajax call,
Source ShoutingCode

Ajax - prevent click on a successful ajax request

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 );
}
});
});

Disable Button while AJAX Request

I'm trying to disable a button after it's clicked. I have tried:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
error: errorhandler,
dataType: 'json'
});
$("#ajaxStart").attr("disabled", false);
});
but the button is not getting disabled. When I remove $("#ajaxStart").attr("disabled", false); the button gets disabled.
While this is not working as expected, I think the code sequence is correct. Any help will be appreciated.
Put $("#ajaxStart").attr("disabled", false); inside the success function:
$("#ajaxStart").click(function() {
$("#ajaxStart").attr("disabled", true);
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
$("#ajaxStart").attr("disabled", false);
},
error: errorhandler,
dataType: 'json'
});
});
This will ensure that disable is set to false after the data has loaded... Currently you disable and enable the button in the same click function, ie at the same time.
In your code, you just disable & enable the button on the same button click,.
You have to enable it inside the completion of AJAX call
something like this
success: function(response){
$("#ajaxStart").attr("disabled", false);
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
},
I have solved this by defining two jquery functions:
var showDisableLayer = function() {
$('<div id="loading" style="position:fixed; z-index: 2147483647; top:0; left:0; background-color: white; opacity:0.0;filter:alpha(opacity=0);"></div>').appendTo(document.body);
$("#loading").height($(document).height());
$("#loading").width($(document).width());
};
var hideDisableLayer = function() {
$("#loading").remove();
};
The first function creates a layer on top of everything. The reason the layer is white and completely opaque, is that otherwise, IE allows you to click through it.
When doing my ajax, i do like this:
$("#ajaxStart").click(function() {
showDisableLayer(); // Show the layer of glass.
$.ajax({
url: 'http://localhost:8080/jQueryTest/test.json',
data: {
action: 'viewRekonInfo'
},
type: 'post',
success: function(response){
//success process here
$("#alertContainer").delay(1000).fadeOut(800);
hideDisableLayer(); // Hides the layer of glass.
},
error: errorhandler,
dataType: 'json'
});
});
I solved this by using global function of ajax
$(document).ajaxStart(function () {
$("#btnSubmit").attr("disabled", true);
});
$(document).ajaxComplete(function () {
$("#btnSubmit").attr("disabled", false);
});
here is documentation link.
The $.ajax() call "will not block" -- that means it will return immediately, and then you enable the button immediately, so the button is not disabled.
You can enable the button when the AJAX is successful, has error, or is otherwise finished, by using complete: http://api.jquery.com/jQuery.ajax/
complete(XMLHttpRequest,
textStatus)
A function to be
called when the request finishes
(after success and error callbacks are
executed). The function gets passed
two arguments: The XMLHttpRequest
object and a string categorizing the
status of the request ("success",
"notmodified", "error", "timeout", or
"parsererror"). This is an Ajax Event.

Resources