I have a page full of different links that each have a class of .post-link.
In the following function, I'd like the line $(this).html('loading...'); to target the specific .post-link div that is clicked. How would I go about achieving this? I feel I should create some sort of variable but I'm a bit lost. Any help would be appreciated.
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$(this).html('loading...'); <--line in question
},
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
Edit
Here is how my HTML is set up:
<a class="post-link"><img src="image.jpg"></a>
Using Alexander's solution, the "loading..." text shows up like this:
<a class="post-link"><img src="image.jpg">loading...</img></a>
Is there a way to make it show like this?
<a class="post-link"><span>loading...</span><img src="image.jpg"></img></a>
Of course given that I wrap the text in span tags?
Update
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel'),
ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$('<span class="loading">loading...</span>').insertBefore($(e.currentTarget).find('img'));
},
success: function(response) {
$('.loading').remove();
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
if ($(window).scrollTop() != 0) {
projectShow();
$('html, body').animate({
scrollTop : 0
},100);
} else {
projectShow();
}
});
Use
$('<span>loading...</span>').insertBefore($(e.currentTarget).find('img'));
or
$(e.currentTarget).prepend('<span>Loading</span>');
because this in beforeSend does not refer to element
You could try something like:
$('.post-link').click(function(e) {
e.preventDefault();
// set a variable as a reference to 'this'
// prefixing variables containing jquery object with a '$'
// as an easy way to spot them in your code
var $self = $(this),
post_id = $(this).attr('rel'),
ajaxURL = site.ajaxurl;
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
beforeSend: function() {
$('#project-wrapper').addClass('activated');
$self.html('loading...');
// use if .post-link is a text element
$self.prepend('<span>loading...</span>')
// if your .post-link is an image
},
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
Although Alexander's answer is better as long as you don't override/re-declare the e
You may have overcomplicated it a bit. Why do it in beforeSend? Just do it like this:
$('.post-link').click(function(e) {
e.preventDefault();
var post_id = $(this).attr('rel');
var ajaxURL = site.ajaxurl;
// do it here:
$('#project-wrapper').addClass('activated');
$(this).find('img').before('<span>loading...</span>');
function projectShow() {
$.ajax({
type: 'POST',
cache: false,
url: ajaxURL,
data: {'action': 'load-content', post_id: post_id },
success: function(response) {
$('#project-container').html(response);
$('.post-container').addClass('fadeInUp');
$('.close-button').addClass('fadeOutDown');
$('#project-wrapper .entry-title').shuffleLetters();
return false;
}
});
}
// I guess you are calling projectShow() somewhere in here
});
In browsers which support ES5 (IE >= 9), you can simply use .bind(this) to get context.
beforeSend: (function() {
$('#project-wrapper').addClass('activated');
$(this).prepend('<span>loading...</span>');
}).bind(this),
Try with this code
$(this).parent('.post-link').html('loading....');
Related
I am trying to post via link. But I think there is a problem. I am not good at Javascript.
I want to send attribute and show with div.
Here is my Code :
<script type="text/javascript">
$(document).ready(function() {
$("#slidingProduct").click(function() {
var aa = $(this).attr('urun_id');
$.ajax({
url: "data.php",
dataType: "POST",
data: {
"number1": aa
},
success: function(json) {
$("#result").html(json.number1);
}
});
});
});
</script>
A
B
O
<div id="result"></div>
You can do something like this:
$(".slpd").on('click',function(){
var aa = $(this).data('urun_id');
var json={"number1":aa};
$.ajax({
url: "data.php",
type: "POST",
dataType:'JSON',
data: JSON.stringify(json),
success: function(result){
$("#result").html(result.number1);
}
});
});
As ids in DOM should be unique, you can specify similar class name to capture click event in a single go and
some modifications in html - It's good to use data-* property of html5:
A
B
O
$(document).ready(function() {
$("a").on('click', function(e) {
e.preventDefault(); // Stop redirection
var aa = $(this).attr('urun_id');
$.ajax({
url: "data.php",
type: "POST"
dataType: "JSON",
data: {
"number1": aa
},
success: function(response) {
$("#result").html(response.number1); // This depends on how you've sent response from server
}
});
});
});
I have try for the following for a long time and i have no more idea now, anyone can help me please.
I just want to reload the current page after add items to the cart, I have try the stupid way by count, promise then and other else, but all fail.
The problem is... the page already reloaded before the item add to the cart...!
The following is my sample:-
$("#Button").click(function () {
var CurrentURL = window.location.href;
var SelectedProduct = $('.SelectedProduct').length;
$('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json"
});
--SelectedProduct
if (SelectedProduct === 0) {
window.location.href = CurrentURL;
$('#CartListContent').slideDown()
}
});
});
$("#Button").click(function () {
var CurrentURL = window.location.href;
var promise = $('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json"
});
promise.done(function () {
window.location.href = CurrentURL;
$('#CartListContent').slideDown()
});
});
});
}
});
I don't know how much control you have over the server side code, but you should let the API handle adding an array of products to cart, that would make it so much faster and simpler. http://jsfiddle.net/hqn3eufa/
$("#Button").on('click', function () {
var selected_products_ids = [];
$('.SelectedProduct').each(function () {
selected_products_ids.push(this.id);
});
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { ids: selected_products_ids },
datatype: "json",
success: function() {
window.location.reload();
}
});
});
You can make use of the success callback of ajax and the reload function:
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json",
success:function(data){
window.location.reload();
}
});
your page reload before the add to cart completes.
use a callback to find out when the add to cart is completed:
$("#Button").click(function () {
var CurrentURL = window.location.href;
var promise = $('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json"
}).success(function () {
window.location.href = CurrentURL;
$('#CartListContent').slideDown()
});
});
});
}
});
Now i use the following way, it is stupid but work:-
Anyother suggestion..!?
var SelectedProduct = $('.SelectedProduct').length;
$('.SelectedProduct').each(function () {
$.ajax({
url: "/ShoppingCart/AddToCart",
data: { id: $(this).attr('id')},
datatype: "json",
success: function (data) {
--SelectedProduct
if (SelectedProduct == 0) {
window.location.reload()
}
}
});
});
This is a relatively novice question. I have the following jQuery function:
$(function ()
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
});
I'm looking to name and parameterize the function so that I can call it repeatedly (with the parameters queryType and divID which are already included in the code). I've tried unsuccessfully multiple times. Would anyone have any insight?
Just stick it in a function
function doAjax(queryType, divID) {
return $.ajax({
url: 'testapi.php',
data: {query : queryType},
dataType: 'json'
}).done(function(data) {
var id = data[0];
$('#'+divID).html(id);
});
}
and use it
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id);
});
});
or
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id).done(function(data) {
// do something more with the returned data
});
});
});
If you're just looking for a simple function to wrap the ajax call give this a try. Place this function above the document ready code.
function callAjax(queryType, divID) {
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data) {
var id = data[0];
$('#'+divID).html(id);
}
});
}
To call the function do this:
callAjax('YourQueryHere', 'YourDivIdHere');
function myFunction(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}
and to call it simply use
myFunction("someQueryType", "myDiv");
function doThis(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}
I have a little function, im trying pass 2 parameters for her, but dont works...
Any idea/sugestion?
Don't have problems with ajax, i have tested this code without parameters, putting direct on the function, but calling her, not works, sorry about the terrible english!!
function myfunction(var_data, var_field)
{
$(function()
{
$.ajax
({
url : "myscriptajax.php",
type: "POST",
data: var_data + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$(var_field).val(data.somevar);
}
}
})
})
}
$("#medicocrm").change
(function()
{
myfunction("crm=","#mediconome");
})
// edited after here for best explanation about.
That works:
$(function()
{
$("#medicocrm").change
(function()
{
$.ajax
({
url : "abertura.ajax.php",
type: "POST",
data: "crm=" + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$("#mediconome").val(data.nome);
}
}
})
return false;
})
$("#participantematricula").change
(function()
{
$.ajax
({
url : "abertura.ajax.php",
type: "POST",
data: "matricula=" + $(this).val(),
dataType:"json",
success: function(data)
{
if(data.status)
{
$("#participantenome").val(data.nome);
}
}
})
return false;
})
\i tried this with first answer...
and that not works:
function verifica(dados,campoid,camponome){
$.ajax({
url : "abertura.ajax.php",
type: "POST",
data: dados + campoid,
dataType:"json",
success: function(data){
if(data.status){
$(camponome).val(data.nome);
}
}
});
return false;
};
$("#medicocrm").change(function(){
verifica("crm=",this.value,"#mediconome");
});
$("#participante_id").change(function(){
verifica("id=",this.value,"#participante_nome");
});
Just do a revamp.
function myfunction(var_data, var_field, elementValue){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + elementValue,
dataType:"json",
success: function(data){
if(data.status){
$(var_field).val(data.somevar);
}
}
});
};
$("#medicocrm").change(function() {
myfunction("crm=","#mediconome", this.value);
});
Here we removed the DOMContentLoaded listener and passed the value of the element through to the function..
You can use $(this).val(); in place of this.value whatever floats your boat.
You have a whole lot of wrappers going on, and your use of $(this) is likely breaking it. Something like this should work:
function myfunction(var_data,$var_field,whatever_this_is_val){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + whatever_this_is_val,
dataType:"json"
}).done(function(data){
if(data.status){
$var_field.value = data.somevar;
}
});
}
$("#medicocrm").on('change',function(){
myfunction("crm=",this,document.getElementById(whatever_this_is).value);
});
Changes:
Unnecessary wrappers removed
Passing of $(this) ... you need to specifiy it
Cleanup syntax to modern use of .done().
Using vanilla JS where easily applied
You should also consider explicitly declaring the page that it calls to be JSON, rather than saying dataType:'json' in your call. Its bulletproof this way, and less work performed on all sides.
EDIT
If you are really just passing the value of the item changed, easiest way to do it:
function myfunction(var_data,$var_field){
$.ajax({
url : "myscriptajax.php",
type: "POST",
data: var_data + $var_field.value,
dataType:"json"
}).done(function(data){
if(data.status){
$var_field.value = data.somevar;
}
});
}
$("#medicocrm").on('change',function(){
myfunction("crm=",this);
});
That way worked!!!!!! With many wrappers, but... Worked!
callajax = (function(origem,dados,campo)
{$.ajax({
url : "abertura.ajax.php",
type: "POST",
data: origem + "=" + dados,
dataType:"json",
success: function(data){
if(data.status){
$(campo).val(data.nome);
}
else{
$(campo).val("");
alert('Não encontrado');
}
}
})
});
$(function(){$("#medicocrm").change
(function(){
callajax('crm',this.value,"#mediconome");
});
});
$(function(){$("#participantematricula").change
(function(){
callajax('matricula',this.value,"#participantenome");
});
});
$(function(){$("#prestadorcodsoc").change
(function(){
callajax('codsoc',this.value,"#prestadornome")
});
});
I am wondering how will I clear my ajax's setInterval if there are zero result found.
here is my code:
$(document).ready(function() {
var imageLoader = {}
imageLoader.render = function(event){
$.ajax({
url: UAI+'/useraccountimages/loadimage',
type: 'post',
data: {
id : UID,
},
success: function(data){
$("#available_images").html(data);
}
});
}
imageLoader.interval = setInterval(imageLoader.render,5000);
imageLoader.render();
});
I'm not sure with the code, just follow the "logic" !
$(document).ready(function() {
var imageLoader = {}
imageLoader.render = function(event){
$.ajax({
url: UAI+'/useraccountimages/loadimage',
type: 'post',
data: {
id : UID,
},
success: function(data){
if (data.is(':empty')) {
clearInterval(imageLoader.interval);
}
$("#available_images").html(data);
}
});
}
imageLoader.interval = setInterval(imageLoader.render,5000);
imageLoader.render();
});
With the function "clearInterval" to stop it. (stopInterval description)