After getting a new page with $.get none of the javascript will run on the new page.
Is there a way to make javascript use the new page too?
Many thanks
Dorjan
Edit: Example:
$(function() {
$('.viewPage').click(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Now this works fine however, the new page's anchor tags won't trigger (lets say it has a .viewPage).
I hope that clarify's the issue.
You need to bind events to your anchors using live:
$('a.something').live("click",function() {
alert('this will still work after a.something has been replaced via ajax');
});
Another way using $.get's callback:
$.get( "page.html", function(data) {
$('#someDiv').html(data);
$('a.something').click(function() {
alert('this will still work after a.something has been replaced via ajax');
});
});
Now that I've seen your code:
$(function() {
$('.viewPage').live("click",(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Yep; there is another jquery ajax method that will take the returned script from your page and execute it. Check the jquery docs.
Related
I have the following jquery code, that pulls json data from a url; however, it is giving me the same quote over and over, instead of random. If I use url directly on browser it does randomize the quote. What am I missing? Thanks
$(document).ready(function() {
$("#getMessage").on("click", function(){
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
console.log(a[0].content + " " + a[0].title)
$("#quote-content").html(a[0].content)
$("#quote-title").html(a[0].title)
});
});
You can either turn off AJAX cache for jQuery, like this:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
//...
});
Or you could change the url for every request (so it doesn't get cached), something like this could work:
$(document).ready(function() {
$("#getMessage").on("click", function(){
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=&"+new Date().getTime(), function(a) {
//...
});
});
});
Also, I don't think you need the callback= parameter
I have the following code with which I used to refresh a captcha image via JavaScript. Is there anyway I can also achieve that using an AJAX request?
<script>
function refreshCaptcha() {
$("#captcha_code").attr('src','captcha_code.php');
}
</script>
<button name="submit" onClick="refreshCaptcha();">Refresh Captcha</button>
Yes it's possible, but then you need to handle session manually!
<script>
$(".RefreshCaptcha").click(function () {
$.post('captcha_code.php', function(data, status){
$("#captcha_code").attr('src', data);
console.log("ajax log: " + status);
});
});
</script>
<button class="RefreshCaptcha">Refresh Captcha</button>
w3shcools ajax.post
You can use the following code.
<script>
$(document).ready(function() {
setInterval(function() {
$.post('captcha_code.php', function(data) {
$('#captcha_code').html(data);
});
}, 1000);
});
</script>
Yes AJAX can be used to update the update the image via Javascript. Because the code already uses jQuery, a simple way would be to use $.post() to post to the PHP script. Presuming that captach_code.php merely returns the image source (e.g. base-64 encoded string), you can set the src attribute to the response value (e.g. in the function updateImage() below).
function refreshCaptcha() {
$.post('captcha_code.php', updateImage);
}
function updateImage(response) {
$("#captcha_code").attr('src',response);
}
See it in action in this phpfiddle. Note - there is no control of the filenames so PHP_SELF is used instead of captcha_code.php.
$.post() returns a jqXHR object, which implements the Promise interface. Because of this, .done() and other similar functions can be used instead of specifying the success callback:
function refreshCaptcha() {
$.post('captcha_code.php')
.done(function(response) {
$("#captcha_code").attr('src',response);
})
.fail(function() {
//fail handler...
})
.always(function() {
//handler for all cases
});
}
See it in action in this phpfiddle.
I have a snippet in my project similar to the one seen below:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$('#this_container').fadeIn();
}
});
The above snippet is working. When thisCondition evaluates to true, the container does fade in. However, I also have the snippet below that is not functioning as expected. It binds to show so that when the container fades in an event will be triggered:
$('#this_container').bind('show', function() {
$.ajax({
...
});
});
Shouldn't the snippet above react to line 5 in the change event handler? Why is the bind method not triggering?
Confirmed that show is not a valid nor jQuery-triggered event.
But you can trigger it yourself!
Try something like this :
$('#this_container').fadeIn("slow", function() {
$(this).trigger("show");
});
The show is not a valid event, neither is triggered by jQuery. You need to construct your script in a different way altogether:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$.ajax({
success: function () {
$('#this_container').fadeIn();
}
});
}
});
So, you can try to bring the AJAX content, and upon a successful request, you can show the container.
try to use :
$('#this_container').fadeIn( "slow", function() {
// Animation complete
$.ajax({
...
});
});
I have a small problem that should be very easy to overcome. For some reason I cant work this out. So the problem is I cannot get a button to link to some jquery. My set-up is as follows (showing the relevant code):
Default.aspx
jQuery:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
});
}
jQuery(document).ready(function () {
getContent();
});
HTML:
<div id="content"></div>
ContentService.vb
<WebMethod()> _
Public Function GetContent(number As Integer) As String
Dim sb = New StringBuilder
sb.AppendLine("<table>")
sb.AppendLine("<tr>")
sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Number</td>")
sb.AppendLine("</tr>")
sb.AppendLine("<tr>")
sb.AppendLine("<td>" & number & "</td>")
sb.AppendLine("<td><a href='#' id='test' class='fg-button ui-state-default ui-corner-all'><img src='" & Context.Request.ApplicationPath & "/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>")
sb.AppendLine("</tr>")
sb.AppendLine("</table>")
Return sb.ToString
End Function
So that's the basics of what I have everything works but I'm not sure how to get the a button (id='test') to get linked to some jQuery. I want it to be pressed and bring up a popup.
I have tried to put the jQuery on default.aspx but this doesn't seem to work unless the button is place in the HTML on that page.
$('#test').unbind('click').click(function () {
alert('Working');
});
I'm sure this is easy to do, but I have been trying for a while and cannot seem to get it to work.
Is the problem that you're trying to bind to the element that ISN'T in existance yet?
are you calling the $('#test').unbind('click').click(function () {
alert('Working');
}); BEFORE the service has returned?
$('#test').on('click', function () {
alert('Working');
});
This will bind the event to the '#test' element once it has been inserted in to the DOM.
As you load the content via ajax, you have to bind to $('#content'). Like this:
$(function () {
$('#content').on('click', '#test', function () {
e.preventDefault(); // if a default action is not needed needed
alert('Working');
});
});
I guess this is about not preventing the default behaviour of the A href tag. Now it will probably link to '#' instead of firing the onclick event.
$('#test').on('click', function (e) {
alert('Working');
e.preventDefault();
});
You could try to wrap this in a document ready, or eventually use the .on binder from jQuery, since it's dynamic content.
Solved
It was a very small thing that caused this. The code to fix this problem is as follows:
$('#test').unbind('click').click(test);
This needed to go inside the function with the json so:
function getContent() {
var data = {
numberID: 1
};
$.jsonAspNet("ContentService.asmx", "GetContent", data,
function (result) {
$('#content').html(result);
$('#test').unbind('click').click(test);
});
}
Thank you to everyone that has tried to help me.
Hey, I'm new to JavaScript so this is most probably going to sound really basic but here goes.
My web page is made up of "modules" which I load into the page with jQuery, so that my JavaScript works with the new content that has been loaded into the page, I have been told to use callback functions.
My problem is though, how do I activate multiple callback functions?
here is some of my code:
function loadLoginForm() {
$('[name=loadLoginForm]').click(function() {
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php", null, loadRegisterForm);
});
}
This bit of code activates the function named "loadRegisterForm" but what do i do if I want to activate more than one?
I've tried a few ways of how I think it would be done but to no avail, also I tried Google but I believe I'm using the wrong terminology.
It may be something like what you need?:
function loadLoginForm() {
$('[name=loadLoginForm]').click(function() {
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php", null, function(data) {
loadRegisterForm_1(data);
loadRegisterForm_2(data);
loadRegisterForm_3(data);
});
});
}
EDIT II:
function loadLoginForm() {
$('[name=loadLoginForm]').click(function() {
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php", null, function(data) {
loadRegisterForm_1.call(this, data);
loadRegisterForm_2.call(this, data);
loadRegisterForm_3.call(this, data);
});
});
}