Trouble with jQuery locator on AJAX response - javascript

I'm banging my head here trying to figure out why this isn't working, so I finally created a simplified version of what I'm going on jsFiddle, and of course it works there.
What I'm doing - a simple AJAX call on hover over an element, and putting that response in a DIV. Here's the code on my site that is NOT working...
HTML
<div class="profileimage">
<a href="#">
<img src="/profilepics/img.jpg" />
<p>Test Here</p>
</a>
<div class="profileInfo"></div>
</div>
jQuery
$(document).ready(function() {
$('.profileimage').hover(function() {
$.ajax({
url:"getProfile.php",
success:function(HTML){
$(this).find('.profileInfo').html(HTML);
}
});
});
});
Also, for reference, all that's in getProfile.php currently is:
<p>RESULTS FROM AJAX</p>
What DOES work is that the AJAX request happens, the result is returned okay. If I replace the line in the success function with alert(HTML), I can see the response. What does NOT work is that the response never makes it in to the profileInfo child element.
I assumed my locator was incorrect, so I created a jsFiddle (HERE) to test. Turns out, the locator works just fine.
So I guess my question here is... if the locator works okay in the jsFiddle, but not in the AJAX request... is there something about the way it's used in an AJAX call that I need to change? I don't see why $(this).find('.profileInfo').html(HTML); shouldn't work just fine regardless of whether I'm using it in an AJAX response or not.
Any thoughts / suggestions are appreciated...

The this is not the right context. To fix this you have multiple options:
You can use context option:
$.ajax({
url:"getProfile.php",
context: this,
success:function(HTML){
$(this).find('.profileInfo').html(HTML);
}
});
or you could use a different selector:
$.ajax({
url:"getProfile.php",
success:function(HTML){
$('.profileimage').find('.profileInfo').html(HTML);
}
});
or you could use jQuery's bind to ensure the correct context:
$.ajax({
url:"getProfile.php",
success: $.proxy(function(HTML){
$(this).find('.profileInfo').html(HTML);
}, this)
});
or you can use closure like this (my favorite):
var self = this;
$.ajax({
url:"getProfile.php",
success: function(HTML){
$(self).find('.profileInfo').html(HTML);
}
});

Try this less elegant but educational approach...
$(document).ready(function() {
$('.profileimage').hover(function() {
var that = $(this);
$.ajax({
url:"getProfile.php",
success:function(HTML){
that.find('.profileInfo').html(HTML);
}
});
});
});

Related

PHP AJAX - Can an <input> element have "action" just like how a <form> does?

Forms have an action attribute to specify where (for example a .php file) to post to. Do <input> elements have the action attribute?
The answer is most likely no. But I wish to know what concept am I getting wrong here?
Is there a equivalent of action for <input>?
The reason I am asking this is that I have a few checkboxes, and I wish to use AJAX to fire something to a PHP file, such that a div changes when the checkboxes are ticked (I don't want a whole page reload). How should I go about doing this?
I am still drafting the code at this stage, but an example can be seen here.
Appreciate your suggestions!
Based on comments it really sounds like you want something to be sent when any number of checkboxes might be changed.
Add an event handler to all of them, serialize() the form and post it whenever any one of them changes
var $form =$('#myForm');
$form.find(':checkbox').change(function(){
var formData = $form.serialize();
$.post('/someFile.php', formData, function(response){
// do something with response
}).fail(function(){
alert("Oops something bad happened');
});
});
Use jQuery AJAX Methods:
AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page.
EX:
$(document).ready(function(){
$("button").click(function(){
// You can call ajax on any event of html element like checkbox checked, dropdown changed
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
$(document).on('change', '#checkboxid', function() {
if ($(this).is(':checked')) {
$('#container').load('pages/somephpfile.php');
}
});
Use .load() on change of checkbox
you cant set which php file to load based on the checkbox status.
Also try
$(document).on('change', '#checkboxid', function() {
$.ajax({
type: 'POST',
url: 'somephp.php',
dataType: "html",
success: function(data) {
$('#container').html(data) //load the data from somephp.php here
}
});
});

Insert text into a div with jquery load

I'm trying to get jquery to load the text from a text file into a div for a blog, but it's not working at all. any help?
this is what I'm using (what I've seen other's use). Also, I'm not testing it locally.
$("#content").load("articlename.txt");
update:
is there any way for it to keep the enters as breaks?
There is a no direct way to get data from external file in jquery.
But via ajax its possible.
$(document).ready(function() {
$("#loadData").click(function() {
$.ajax({
url : "articlename.txt",
dataType: "text",
success : function (data) {
$("#content").html(data);
}
});
});
});
$(document).ready(function() {
$("#content").load("articlename.txt");
});
Wrap your call inside document.ready.

Why does my JS/JQuery code only work in a web browser's console?

The $(element).scroll(function(){}); function isn't working for me when I put it into a js file but when I enter it into the console (just the scroll func), it works just fine.
I'm trying to do a scrolling pagination.
I've looked through my other js files and the only thing that I think could be conflicting is another one of the files has a $(document).ready(function(){}) but I'm pretty sure that's not the problem. I'm also using Dropkick to make pretty dropdowns but I doubt that's it either.
Here's the code, almost verbatim. It's basic for now until I can figure out how to get it to load.
$('#main').scroll(function(){
if(($('#main').prop('scrollHeight'))==
($('#main').scrollTop()+$(document).height()-10)){
//^there's a strange 10px empty space that needs to be accounted for
$('#loading').show();
$('#main').css('overflow','hidden');
addMore();
}
});
$(document).ready(function(){
addMore();
});
addmore.counter=0;
function addMore(){
$.ajax({
async: 'true',
url: 'http://mywebsite.com/bc/get',
type: 'post',
data: ({'offset':(addmore.counter)}),
success: function(data) {
$('#scrollingpagination').append(data);
$('#loading').hide();
$('#main').css('overflow','scroll');
addmore.counter++;
}
});
}
And here's the HTML (not verbatim, but same idea)
<!--I'm only including the "main" div that shows the content.-->
<div id='main'>
<div id='scrollingpagination'></div>
<div id='loading'></div>
</div>
Thanks guys, I really appreciate it!
try keeping
$('#main').scroll(function(){
......
})
inside document.ready. i think it was called before the dom was ready

How to update a value by jQuery AJAX

I load content of a page by jQuery AJAX as
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php?start="+$('#lastid').text(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
In the current document, I have <div id="lastid"></div> and in the external php file <div id="start"></div>
The value for id="start" is updated from database, and it will be transferred to id="lastid". However, this code only works for FIRST click. For default <div id="lastid">1</div>, when clicking the button (id="more") it will read load.php?start=1 and updates the current document to <div id="lastid">11</div> (it's visible). But the second click will not load load.php?start=11
It seems that $('lastid') well reads the default value of <div id="lastid"></div>, but NOT when it has been updated by $("#lastid").empty().load('html #start')
How can I modify this code to work for subsequent clicks?
Wow, what a mess! Let's clean up a bit :)
You need to get rid of the id, as an id has to be unique and if you load another div with id lastId into your site, jQuery will not know which id to get. If you have many divs, each containing the id, you can just read the last id by using ('div:last').text();
So your ajax would look like this:
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php",
data: "start="+$('div:last').text()
success: function(html){
$("#results").append(html);
}
});
});
});
I also don't know what you do with the last line in the success, as load should be used to load data from the server with ajax, what is what you do by using $.ajax(). Also load() takes at least an url as parameter, see here.
try .live() function instead of .click()
Mate,
What I see from you code is that you are attaching an event once the page is loaded. And this creates a static call with static values that don't get updated as you continue.
My suggestions is to use a function that will feed an Id dynamically to your ajax call as follows:
$(document).ready(function(){
$(document).on("click", '#next', function(event){
$.ajax({
url: buildurl(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
function buildurl()
{
return "load.php?start="+ $('#lastid').text();
}
This will force your event to always call this function and the function to get a fresh value from lastid.
Regards
you have to change your success function because you have multiple #lastid when clicking twice.
try something like:
success: function(html){
$("#lastid").removeAttr("id"); // remove's the id from #lastid
$("#results").append(html); // appends the new one
$("#lastid").empty().load('html #start');
}

jquery call after success

I am calling jquery ajax call,
$.ajax({
type: "post",
url: formLink,
cache: false,
data: ......,
success : function(responseHTML) {
$(".abc").html(responseHTML);
}
});
Now in ".abc", lets say,
<html>
..............
</html>
<script>
alert("11"); //Not getting this alert
</script>
even tried with
$(document).ready(function () {
alert("11");
});
Not able to get alert even after the success, Please help
Thanks in advance
if the doctype is not of html5 then you will need the type attribute on the script tag
oh.. and i hope you are not returning <html> tag in the response - only return a fraction of the html you need.
and if you can - return it with attributes that can be analyzed at the success call and init your js function from there
also remove the $(document).ready this event happened long before your ajax call, and will not happen again when you refresh a part of the page
Try adding dataType:"html" to your ajax params.
Try replacing
<script>
alert("11"); //Not getting this alert
</script>
With
<script type="text/javascript">
(function () {
alert('11');
})();
</script>
Not 100% sure it will work, but worth giving it a shot:
You can try returning your javascript code in a function, once the '.abc' html has been seen, call your return function name.

Categories