basic ajax function not working - ajax

i'm learning Ajax and i'm facing some problem with this very basic function:
function fetchData(url, objectID){
var pageReqtest=null;
if(window.XMLHttpRequest)pageRequest=new XMLHttpRequest();
if(window.ActiveXObject)pageRequest=new ActiveXObject("Microsoft.XMLHTTP");
else return false;
pageRequest.onreadystatechange= function(){
var object=document.getElementById(objectID);
object.innerHTML = pageRequest.responseText;
}
pageRequest.open("GET",url,true);
pageRequest.send(null);
}
And then i have:
<div id="control" onclick="fetchData('data.jsp','message');">Click here for Ajax!</div>
But unfortunatelly its not working, the function though is correctly called.
I have my project in Eclipse and i'm running this on Tomcat 6, the page data.jsp its a single line of html, the data.jsp is positioned at the same lavel as the page where the javascript function is written
Do you have some advice?

beside wrong spelling as mentioned by lonesomeday
you also have missing parameter here var object=document.getElementById();

Looks like others beat me to it, but in any case, here is working fiddle: http://jsfiddle.net/smendola/BcMMn/
As they said, typos...

My best bet is that it is a syntax error caused by your misspelling of function:
pageRequest.onreadystatechange= fucntion(){
This would cause the Javascript not to be parsed, so your function would never be defined.
On a different note, there are a couple of other little errors that, while they might not prevent your code working, might make your life difficult.
var pageReqtest=null;
Elsewhere you call the variable pageRequest. Be consistent: at the moment, you are creating a global variable called pageRequest and completely ignoring the local one pageReqtest.
if(window.XMLHttpRequest)pageRequest=new XMLHttpRequest();
if(window.ActiveXObject)pageRequest=new ActiveXObject("Microsoft.XMLHTTP");
else return false;
If the browser has both window.XMLHttpRequest and window.ActiveXObject, you will create both, first the XMLHttpRequest object, then you will overwrite it with the ActiveXObject. This isn't what you want – it's suboptimal and it's better to use the proper XMLHttpRequest if it's available.
The quick way to do this is to make the second line else if at the beginning.
And you miss out the id in the getElementById call:
var object=document.getElementById();
I think this should be:
var object = document.getElementById(objectID);

Related

can.js validate method not working

Could anybody help me calling a validation function in can.js?
I'm adding can.jquery.js and can.map.validations.js
and then create such a small example:
var mymap = can.Map.extend({
init: function () {
this.validatePresenceOf('myfield'); // this line reports an error
}
});
when loading page with this script, I get an error in browser:
"Uncaught TypeError: undefined is not a function"
Actually any this.validate* function does not work
After some research I notice that when I put this code under
$(document).ready{}
it works, but if I put it into .js file and load via tag - browser reports an error.
And I'm not going to write all of my js code in the page itself
see here it tells pretty clearly(helped me last time) that you have to use $document.ready() or else it wont work, so try making a new file.js, have $document.ready() contain all your todo-code, and link it up, I hope I am helpful in this regard, if not then bug me up I wont mind at all :) ..
Commenting it late but anyway - it didn't work for me in either case so I just took the sample from http://jsbin.com/jofeq/5/edit?html,js,output - and copied it to my code. Surprisingly it worked after copying - not sure what was wrong on my side.
In that example it looks like this:
var Person = can.Map({
init: function () {
this.validatePresenceOf('firstName');
this.validatePresenceOf('lastName');
}
}, {});
and it works without document.ready tricks or anything else - just included into body tag

SiteCatalyst : Tracking Custom links on Webkit browsers

My query is that I have a link that redirects to another page. In webkit browsers, how to force the sitecatalyst server call (script execution) to finish before the redirect happens?
I am using sitecatalyst for a portal. I have
configured the custom link call to include the doneAction parameter for
successful call completion on webkit browsers (As mentioned in Adobe guide).
The custom link code for onClick event of button is as below:
<script language="javascript" >
function search(keyword)
{
var s=s_gi('testing');
s.linkTrackVars="prop11,events";
s.linkTrackEvents="event6";
s.prop11=keyword;
s.events="event6";
s.tl(this,'o','Search',navigate());
window.location=searchresults.html;
}
</script>
<script language="javascript" >
function navigate()
{
return false;
/*To induce a delay to ensure that image request is sent to Adobe before the
user leaves the page.(As given in Adobe guide - code release H.25))
Code version H.25 (released July 2012) includes an overloaded
track link method ( s.tl ) that forces WebKit
browsers to wait for the track link call to complete.)*/
}
</script>
However, even after this, I am getting error in custom link tracking. The redirect happens before the call can complete.
Please help on the same. Thanks in Advance.
Regards,
Harshil
Okay so firstly there are a number of issues with how you implemented it. Here is an example of how it should look like:
search
<script type='text/javascript'>
function search(keyword) {
var s=s_gi('testing');
s.linkTrackVars="prop11,events";
s.linkTrackEvents="event6";
s.prop11=keyword;
s.events="event6";
s.tl(this,'o','Search',null,navigate);
return false;
}
function navigate(){
window.location="searchresults.html";
}
</script>
Some points
You didn't actually post the link or whatever you are using that calls the search function so I have a link shown as an example.
You passed the navigate function as the 4th argument when it should be the 5th (with a null or blank string as a placeholder for the 4th)
It should be navigate not navigate(). The way you did it, you are making a call to the function and passing the result of the function as an argument. s.tl requires the actual function or reference to a function, and it will make the call to the function. In fairness, the Adobe document is typoed: it shows the example wrapped in quotes which doesn't work.
The redirect should be placed in navigate, not in search.
Replace the link href with javascript function
function trackLink(e) {
nextUrl = e.href;
e.href = "javascript:sendData('" + nextUrl + "')";
}
function sendData(url) {
s.tl(this, "o", "Link Name", null, function() {
window.location.href = url;
});
}
or try out the following
function sendData(obj) {
s.tl(obj, "o", "Link Name", null, "navigate");
return false;
}
Link
Link tracking is a dinosaur form of tracking as the numbers are barely accurate these days if you are not putting analytics before user experience. What I don't understand is that why don't you measure this on the next page instead of the link, unless you have no control over the next step?
As for your question: Previous examples on how to prevent link following before event is executed are quite solid, but remember if you have other JS code binded, be sure not to break it. As for the syntax, you can pass all variables to s.tl function as an object without setting linkTrackVars and linkTrackEvents for the s-object, which might have negative effects on events if case you use the code on dynamic pages.
E.g.
...
var data = {
linkTrackVars="prop11,events",
linkTrackEvents="event6",
prop11=keyword,
events="event6"
};
s.tl(this, "o", "Search", data, "navigate");
...
Note: You can't actually use props and events together in standard reporting. As per the code you pasted in comments to Crayon I can see that you are using eVars, so I assume that the example was not that accurate.

AJAX Loader doesn't stay untill the new content is loaded

I am using AJAX functionality to make my WordPress pages load in real time. I use the following approach to make it load in real time
var toLoad = $(this).attr('href')+' #container';
$('#container').slideUp('300',loadContent);
$('#load').remove();
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#load').fadeIn('normal');
window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);
function loadContent() {
$('#container').load(toLoad,'',showNewContent())
}
function showNewContent() {
$('#container').slideDown('400',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
The problem i am facing is that the loading... text appear for half a second and the old content appears again.. and then after 4-5 seconds, it just replaces the new content with the old one.
How can i keep the Loading Text until the content is fully loaded.
Question is not perfectly clear to me,
But,
$('#container').load(toLoad,'',showNewContent())
should be changed to
$('#container').load(toLoad,'',showNewContent)
and,
$('#container').slideDown('400',hideLoader());
to
$('#container').slideDown('400',hideLoader);
We pass the function reference ( we dont call them )
Also, I dont think there's any .fadeIn('normal').
It would be either .fadeIn('slow') or .fadeIn('fast')
Also,
lines following this
$('#container').slideUp('300',loadContent);
do not wait for animation completion. They gets called instantly.
I guess, you would want them to put in loadContent function

Issue submitting wysiwyg data through Ajax

I am Using Cl Editor On a Cms in a working on, Everytime i submit data through ajax i am having problems with it.
Let's say i write 10 lines in my wysiwyg editor but i only receive 3 or 4 in php, after some debugging in firebug what i have noticed is the html i am sending through ajax contains a span with class "Apple-converted-space" <span class="Apple-converted-space"> </span> i am able to get everything before this span, but the text after this span is missing. I have no idea what it is. Let me write my code for better understanding.
To get cleditor data
var data = $(".cleditorMain iframe").contents().find('body').html();
Ajax Form Submission
if(window.XMLHttpRequest)
{
xmlhttp = new window.XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == '4' && xmlhttp.status == '200')
{
}
}
parameters = 'data=' + data
xmlhttp.open('POST', 'libs/make_procedure.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
return true;
I have also tried jquery ajax method.. same problem exists there, so please do not ask me to use the other way to submit data via ajax.
Thanks
You may want to check whether it is javascript that is not sending correct data or your backend that is not able to receive it.
So first you should debug in javascript by writing an alert(data); statement right after you get the data from that cieditor control, and see what do you get there. Use Firefox and you can also copy the html using mouse pointer from the alert box. (which is not possible in IE)
You should also check the cieditor specs to see if there is any easier way to get data in javascript.
You may also want to consider using CKEditor.
You are posting the data without escaping the contents of the data. Since the & is the seperator for different fields in a post, data will contain only the part up untill the first &. Use encodeURIComponent to escape the data value.
Change the line
parameters = 'data=' + data
to
parameters = 'data=' + encodeURIComponent(data);
See also: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent

Detect AJAX Request

On my website I have mouse over and mouse out events set up on an HTML table. These events trigger ajax requests, and perform certain actions etc. However, i want to be able to not trigger a second request if one is already running. So, is there away to detect these requests, and therefore avoid a second. Incidentally Im using the jQuery $.ajax()
if it helps at all.
Thanks in advance
Chris
I'd try something simple like:
var requestMade = false;
function yourAjaxFunction(){
if(!requestMade)
{
requestmade = true;
$.ajax({
url: "page",
success: function(){
requestMade = false;
}
error: function(){
requestMade = false;
}
});
}
}
You can use the success: and error: settings to change the variable back to false.
I have never used the error so you may have to include some other things in it, but this is the general idea.
For this suppose I'd use ajaxStart() and ajaxStop() which would change specific variable ajaxRunning which could be checked before sending the request (maybe in ajaxStart() directly?)
Set global or local static variable to true when first ajax is about to trigger, than add if before triggering the second one ;) Than after one request is finished, set this variable to false

Resources