It ended up being the $(document).ready was missing. Now that I added that the returned html does not seem to want to display. Is there something wrong with the below code?
success: function(data){
jQuery('#response').empty();
var response = jQuery(data).find('#response').html();
jQuery('#response').hide().html(response).fadeIn();
jQuery('#loading').remove();
}
It may be because "#userbar" isn't available in the DOM yet. Is your script nested within a document.ready event? Like this:
jQuery(document).ready(function() {
var username...
});
Or, the shortcut:
jQuery(function() {
var username...
});
Or the super shortcut:
$(function() {
var username...
});
Is uvhclan.com the same domain of the call? If it is not, you can not make the call because of the Same Origin Policy
If it is the same domain, an error would cause the page to submit and not cancel the submit. Look at the JavaScript console and see if there is an error.
I fixed it, it was the var response = jQuery(data).find('#response').html(); I was looking for the wrong div.
Related
Here's my code:
<script type="text/javascript">
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username() {
$("#check_username").html('<img src="images/site/ajax-loader.gif" />username avilable??').delay(5000);
var usernametotest = $('#username').val();
$.post("backend/username_available.php", { username: usernametotest})
.done(function(data) {
$("#check_username").replaceWith(data);
});
}
</script>
I use this code for checking with AJACX the availability of a username in my form.
It works perfect but just once. When an username is occupied and I change the username, no AJAX checks are done after the first one? The text "username already exists" (in the variable data), is not replaced by "username ok".
This JavaScript is added just before the </html> tag.
Your code looks fine - see this jsfiddle with an alert on the usernametotest value for more visibility
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username(){
$("#check_username").html('username avilable??').delay(5000);
var usernametotest = $('#username').val();
alert('posting username ' + usernametotest);
$.post("backend/username_available.php", { username: usernametotest} )
.done(function(data) {
$("#check_username").replaceWith( data );
});
}
The post requests are being made every time with the correct payload, so no problems there (check browser developer tools e.g. Network tab / XHR in Chrome)
Must be an issue with the response coming back from backend/username_available.php? Check the response of the first request vs the rest, and the difference and hence the problem will probably jump out at you.
Whenever you replace an element... and here you do just that...
$("#check_username").replaceWith( data );
all those element's handlers are lost. So change() no longer works. To be able to use it again, you just need to bind again the element after it has been rewritten:
$('#username').change(check_username);
Or bind the handler to a parent and delegate it:
$('#username').parent().on('click', '#username', check_username);
(I feel that a class selector would work better - call it superstition on my part)
You could try this:
$('#username').on('change', function() {
// write your code here
});
I'm trying to run two js functions(i'm using jquery) in the document.ready(), but only runs one. Here is my code:
$(document).ready(function() {
show_properties();
table_events();
});
the functions are written in the same js file, but only show_properties() is loaded when the website loads. I tested in the firebug console to write
table_events()
and the console tells me "undefined", but after that the function gets loaded and the ajax calls and everything inside that function starts to work.
Why is that? How can I fix this behavior?
thanks.
Here are the functions I want to run:
function table_events(){
$.ajaxSetup ({
cache: false
});
var wait = "<img src='../images/loading_red_transparent.gif' alt='loading...' style='display:block;margin-left:auto;margin-right:auto;'/>";
$('.apartamentos tr').on('click', function() {
alert("hola.")
var id_propiedad = $(this).find(".id_propiedad").html();
var nombre_propiedad = $(this).find(".nombre_propiedad").html();
//$('#property_information').hide('slow');
$("#property_information")
.html(wait)
.load('properties_info.php',{'nombre_propiedad':nombre_propiedad,'id_propiedad':id_propiedad});
//$('#property_information').show('slow');
});
}
function show_properties(){
$.ajaxSetup ({
cache: false
});
var wait = "<img src='../images/loading_red_transparent.gif' alt='loading...' style='display:block;margin-left:auto;margin-right:auto;'/>";
$('#busca_propiedades').on('click',function(){
var user_id = $('#user_list').val();
/*var data = $.ajax({
url: "properties_list.php",
type: 'POST',
data:{ 'user_id': user_id },
cache: false,
async: false
}).responseText;
});*/
$('#lista_aptos')
.html(wait)
.load('properties_list.php',{'user_id':user_id});
//alert(data);
});
}
EDIT:
after some debugging with console.log , i found out that this code is the one that's not executing when the webpage loads:
$('.apartamentos tr').on('click', function() {
alert("hola.")
var id_propiedad = $(this).find(".id_propiedad").html();
var nombre_propiedad = $(this).find(".nombre_propiedad").html();
//$('#property_information').hide('slow');
$("#property_information")
.html(wait)
.load('properties_info.php',{'nombre_propiedad':nombre_propiedad,'id_propiedad':id_propiedad});
//$('#property_information').show('slow');
});
apparently, this function() is the one that doesn't run when the webpage loads; but when I write again in the console
table_events()
THEN the code inside this function runs when I click in the tr of the table.
Are $('.apartamentos tr') elements loaded with the load call in show_properties?
If yes then the problem is due to the fact that when table_events is executed, tr elements are not yet inserted in the #lista_aptos (cause load uses ajax, that's asynchronous).
To check please add
console.log("trs count: ", $('.apartamentos tr').size());
on top of your table_events function.
To fix you should pass table_events as completetion handler to load call:
$('#lista_aptos')
.html(wait)
.load('properties_list.php',{'user_id':user_id}, table_events);
Old response
You said "...after that the function gets loaded and the ajax calls..."
Keep in mind that ajax calls are asynchronous.
If you define the table_events function inside the ajax response handler, also if you do something to put it in a scope visible from the referencing function, the attempt to call table_events may occur before the table_events definition.
or, as Raghavan says, there's an error thrown from show_properties that prevents the execution of table_events. But better if you try to debug with console.log("text") instead of alert (alert is blocking and it will hide you problems from asynchronous calls)
please, try to make a example on http://jsfiddle.net/
If the console returns "undefined" that means the function exists, but it's returning undefined as a result.
Your function needs fixing, $(document).ready() is probably fine.
Try calling table_events() at the last line in show_properties() and see if that works.
A few things to check:
Does table_events exist in the scope of $(document).ready?
Is show_properties possibly raising an error?
This may be a good case for "alert debugging":
$(document).ready(function() {
show_properties();
// You might also put an alert at the very end of show_properties.
alert('show_properties called; now calling table_events()');
table_events();
alert('table_events called; document.ready done');
});
There is probably an error in the table_events function. Try debugging using simple alert statements.
I am attempting to load a .js file hosted online after a jquery click event. First, am I doing this right? Will all the javascript be applied only after a link is clicked?
$(document).ready(function() {
var clickHandler ="file.js";
$('a').click(function() {
$.getScript(clickHandler, function(data, textStatus, jqxhr) {
console.log(data);
console.log(textStatus);
console.log(jqxhr.status);
});
});
Edit: I just checked the console and it is loading the file but giving me a 403 Forbidden message. Why is this happening? Do I need to have some text in my header to refer to?
EDIT 1:
Misread the jQuery code -- this part of the answer doesn't apply:
There are ways to add Javascript file to an existing document, but it isn't as simple as you are trying to do.
This discussion can explain that: How to dynamically insert a <script> tag via jQuery after page load?
The other solution is to put the contents of the Javascript into its own function, include that on the page normally and then run that function in your click handler.
Edit: Expanded answer
Lets say that you have some fairly simple code in your file.js like this:
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
This code will, since it is not wrapped up in a function, will run (or try to run) as soon as it is loaded. It will only run once every time it is loaded.
However, if you wrap it up in a function, like this:
function colorFooz() {
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
}
Then the code will not run until the function is called. It will load and be ready to be called later.
Error 403
The first thing to do is figure out why are getting the error 403.
At this stage, that has nothing to do with Javascript, jQuery or AJAX. Simply the problem by trying to load that Javascript file directly in your browser, by typing something like this utnil your URL:
http://example.com/file.js
Changing the URL to your website and path of course. At this point, you should still be getting the 403 error, but you can now check your server logs to see what error is written there.
I found a page that gives a guide to tracking down 403 errors here: http://www.checkupdown.com/status/E403.html
((PS: If I had to randomly guess at the reason why you are getting the 403 error, I'd say that you don't have the path file file.js correct. Depending on your structure and various includes, it may be calculating the relative path incorrectly.))
The function you pass to click() is a callback and is only executed when the element is clicked. So yes, you've got that part right.
I'm trying to load a page using the load() function, the problem is that javascript code on that page is being executed when loading. I use this:
$('#itemid').load('thepage.php #selector', function() {
MY CODE HERE
});
how can i prevent the javascript code from being executed and load only the HTML part that i want?
Use .get() or .post() and process what you get back. Pull the script tags out of your returned code before you append it to the page, or just pull out the code you want:
$.post('thepage.php', {
data: myData
}, function(data) {
var myHTML = $(data).not('script');
$('#itemid').html(myHTML);
});
Or:
$.post('thepage.php', {
data: myData
}, function(data) {
var myHTML = $(data).filter('#selector');
$('#itemid').html(myHTML);
});
Demo: http://jsfiddle.net/jtbowden/wpNBM/
Note: As you mentioned, using a selector with load should accomplish the same thing, as you see in the example. So, if it isn't working this way, something else is going on.
Not sure if I have understood the problem correctly, but you could remove the javascript and just have the html. I assume you want to js bindings to happen on the new page though. So when you load the new page, in the callback, you could call a function that applies the needed bindings.
function applyAfterAjax(){
$(this).find('element').click(function(){alert('clicked');});
}
$('#itemid').load('thepage.php #selector',applyAfterAjax);
I'm trying to have a setInterval function to use .live() to get information from dynamic content loaded with AJAX. Here's what I have.
var auto_refresh = setInterval(
function () {
var msgid = $(".msgid:last").attr("id");
alert (msgid);
}, 5000);
Obviously this does not work on content that is loaded with AJAX. I can't seem to find any event that could be used for the live() function in this case. All I need is to fetch the last msgid that is loaded on the page every 5 seconds.
Any advice?
Thank you in advance.
As the guys mentioned as comments, your code seems to work, so I can only assume that you want a different way to handle it, perhaps something a little more 'jquery-esque'?
If all your requests are similar, and you know how to parse the response, you could try having a global handler...
$('body').ajaxSuccess(function(e,x,o) {
console.log(e);
console.log(x);
console.log(o);
})
as seen on the jquery website