jquery call after success - javascript

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.

Related

PHP Output Not Appearing in HTML

I have made some code to post the output of a PHP file showing the music I have been recently listening to on Spotify.
The HTML, CSS and JS (for the spotify.php file) are included in this fiddle.
The JS within my index.php file is:
<script type="text/javascript">
function get_spotify() {
$.ajax({
type: 'POST',
url: 'https://theobearman.com/cv/modules/spotify.php',
data: {
request: 'true'
},
success: function(reply) {
$('.now-playing').html("" + reply + "");
}
});
}
window.onload = get_spotify;
</script>
My issue is that the output of the .php file is not showing up under the 'Music' header on my website.
This was working a few days ago, so I'm not sure why it is not working now.
Thanks in advance for any help,
Theo.
Try
$(document).ready(function() {
get_spotify();
});
instead of window.onload = get_spotify, which may run before the element is rendered on the page.
Try using a $(document).ready() to call your function instead of window.onload = ... this ensures that jQuery has correctly been loaded.
Example: $(document).ready(get_spotify);
I visited your site and everythings seems to be fine, only problem is that your function is not gettng called, I tried it from console and works perfectly
After having a look at your website code I found the problem.
You can have only one window.onload in one page but you have two of them so that's why it is not working.
Here is code of your first window.onload, put the get_spotify in here:
window.onload = function() {
get_spotify();//INSERT HERE
var elevator = new Elevator({
element: document.querySelector('.elevator-button'),
mainAudio: 'https://www.theobearman.com/cv/music/elevator-music.mp3',
endAudio: 'https://www.theobearman.com/cv/music/ding.mp3'
});
And also put get_spotify function body and prototype above this onload call.

Trouble with jQuery locator on AJAX response

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

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

AJAX that calls a "parent" function

I've seen a few questions like the one I'll ask but nothing identical. I have two html files, main and today. What I want to do is load today.html via AJAX into a child div in main.html. Sometime after load, I would like to call a function that resides in main.html from today.html
Within Main I have this function:
function drawCircle (size){
alert('DRAWING');
}
This AJAX load:
$("#leftofad").ajax({
url: ":Today.html?r="+genRand(),
type: 'GET',
success: function(data) { },
error: function() { alert('Failed!'); },
});
And this div:
<div id="leftofad"></div>
In Today.html I have
<script type="text/javascript">
$(document).ready(function(){
drawCircle (100);
});
</script>
The load is going well but Today.html doesnt seem to recognize the drawCircle function. I've tried several precursors including this., window., and parent..
I understand that I can use the callback method of the AJAX loader in jQuery but I don't necessarily want to call drawCircle when the load is complete. I may want to wait a bit or do it as a result of an action from the user. Is it possible to reference these functions from an AJAX-loaded div? If not, can I use an alternative method like events and listeners to fire the drawCircle function?
Since you will be loading JS into your page, try calling the function directly?
(The ready function won't run as the main page is already loaded)
Main.html
<script type="text/javascript">
function drawCircle(size) { alert("DRAWING" + size); }
$(function() {
$("#leftofad").load("Today.html?r="+genRand(), function() {
alert('loaded successfully!');
});
});
</script>
<div id="leftofad"></div>
Today.html
<script type="text/javascript">
drawCircle(100);
</script>
If this doesn't work, I strongly suspect that JavaScript returned in an AJAX call is not executed.
In this case, refer to: How to execute javascript inside a script tag returned by an ajax response
$("#leftofad").ajax is not proper.
jQuery's $.ajax function does not use a selector.
What you can use is load:
$("#leftofad").load("Today.html?r="+genRand(), function(){
alert('loaded successfully!');
});
Everyone here has some good answers, but I believe there is a knowledge gap and we are missing some information. If I were you, I would add an alert to the script in the Today.html file right before the drawCirle. Then I would run this page using IE or Chrome dev tools or Firebug in Firefox. When the alert is displayed you can put a breakpoint in the javascript code. Then check your global scope to try and locate drawCirle...
Sorry this is not an exact answer, but with javascript files you need to use debugging tools for this.
while there isn't really a document.ready function for a div, there is a hack that works just as if so:
create your returning data as a full html page:
<html>
<head>
<script type='text/javascript'>
$(document).ready( function () {
do-this;
to-that;
....
});
</script>
</head>
<body>
<%
your possible vbscript
%>
the rest of stuff to be loaded into that div
</body>
</html>
Then, you can have as many cascading div loading from different page loading and .... rinse and repeat ... forever .... EXPERIMENT with different DOCTYPE to see the different results.
EDIT:
Then, of course, you load the original MAIN with
$('#thedivid').load('url-of-the-html-returning-page');
Which, in turn, can have the VERY SAME call in the returning page document.ready as, for example; $('#thedivid-inthereturningdata-html-page').load('url-of-the-html-of-the-child-process-for-whaterver); .... and so on.
Go ahead, PLAY AROUND and make wonderful ajax based applications ....

Javascript doesn't load after AJAX call

Ok the following HTML code is parsed when I load a page:
<div id="clip-wrapper">
<script type="text/javascript">
alert("bla");
</script>
</div>
This obviously leads to an alert saying "bla", after my AJAX call, the parsed HTML code looks like this:
<div id="clip-wrapper">
<script type="text/javascript">
alert("ajaxbla");
</script>
</div>
This on the other hand, doesn't result in an alert. Why? And how do I fix this?
If there are any scripts loaded into your dom from an Ajax call, they will not be executed for security reasons.
To get the script to execute, you'll need to strip it out of the response, and run it through eval
Ideally though, you'll want to run your script as a callback for when your ajax request completes. If you're using jQuery, this would be the success event of your ajax call, and if you're doing it natively, it would be the readyStateChange event of your xhr object.
EDIT
If you really want to opt for the eval option, you could try something like this:
document.getElementById(contentDiv).innerHTML = xmlHttp.responseText;
eval(document.getElementById("clip-wrapper").innerHTML);
put you code in
$(document).ready(function()
{
alert(msg);
});
or make use of readysatchange event of XMLHttp object.
XMLHttpobject.readyStateChange( furnction() { alert('msg'); } );
Edit
if you are using jquery than go for
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
here in sucess event you can write your code which get executed once you are done with the ajax.
any code inside body in between script tag will executed only while loading the document.
in ajax call,make use of callback or success: or oncomplete: to handle the ajax response if you are using jQuery.
You mean the second html code is coming as an ajax response?? Did you even inserted the html to the current page?
Something like,
document.body.innerHTML = ajax_response;
But even with innerHTML replacement I don't thing the script inside it will be auto executed. The browser will parse the script but won't auto execute it. (For eg, if you have a function definition in the html, after the ajax call you will be able to call those functions)
Another option is to use document.write, it will replace the whole page content with the new html and the script tags in it will be auto executed.
document.write(ajax_response);
Hope this helps,

Categories