Loading Varying Number of files with Ajax - ajax

I have an HTML page that dynamically loads one to many HTML snippets that are used as modal forms on the page. The page comes out of a CMS, so the business users can decide "I want one form on this page" or "I want 6 forms on this page". Each of the links and it's loading info need to be a module that goes together and can be put on any page. When each of these links are chosen on the page, I'm outputting a snippet of code that will call an Ajax load script when the page loads.
Snippet Example:
<script>
$(document).ready(function()
{
load('/web_fragments/file.html', 'content_item1');
$('#item1').click(function(){
$('#rmi_item1').dialog("open");
return false;
});
$('#rmi_item1.modal').dialog({autoOpen: false, modal:true,
dialogClass:'modal', width:590});});
</script>
Request More Information
<div id="rmi_item1" class="appLvl mod modal dialog">
<div id="content_item1">
</div>
</div>
Each of the IDs and divs on the page have unique identifiers, I've just simplified them here for ease of reading. The problem is the load method. I have no idea how many of these will be on the page, so I can't really create multiple load methods. If there is only one item on the page, it all works great. Here is the load method I have now. I'm new to Ajax/jQuery, so I extend my apologies and beg you to be kind! :)
function load(url, target)
{
document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {targetDiv(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function targetDiv(url, target)
{
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
}
}
}
Any suggestions or help is welcome as I am now officially about really to lose my mind over this error! Thanks!

I think your problem comes from this line
req = new XMLHttpRequest();
Here you use (and implicitly declare) a variable req. This variable is declared in the
global scope (window object)
Make this var local to the load function, like this
var req = new XMLHttpRequest();
This will prevent the second snippet to overwrite the req var and trash the first
snippet request that was just fired but not yet recieved.
Have a look to the jquery load method. This should make your code smaller and avoid
this problem.
hope this helps,

Related

iScroll Ajax content

i have problem with refreshing content in wrapper after it is loaded by ajax.
When i check with firebug - XHR is showing request and i can see elements loaded but it isn't showing on page.
This is what i am using for pullDown function to get ajax content
function pullDownAction () {
setTimeout(function () {
var el, li, i;
el = document.getElementById('thelist');
var http = new XMLHttpRequest();
var url = window.location;
http.open("GET",url,true);
http.send();
myScroll.destroy();
myScroll = null;
loaded();
}, 1000);
}
It looks like as content is stuck between showing on webpage and ajax request.
Any idea?
myScroll.refresh() (instead of .destroy() and recalling "loaded()") should do the trick!
If you're using IScroll4 you can try to use the checkDOMChanges:true option of iscroll.
If it still won't work - it could be a CSS issue caused by the scroll-wrapper (#scroller) not expanding with its content. (float,position:absolute; or something like that)
EDIT: it seems to me as you're not handling a responseText of the request at all!
According to this example you need an event handler for the onreadystatechange event:
http.open("GET",url,true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText); //handle this response! (i.e. writing to an element's innerHTML)
}
};
http.send(null);

HighChart not working when called by ajax

Hi guys i have a page which is working perfectly it contains a highchart. I want to show this page on the existing page through an ajax call. My ajax is working perfectly but the highcharts are not displaying when i make ajax call.
link of my highchart is
http://www.rahatcottage.com/AI/J/examples/line-log-axis/index.php
And My ajax script goes here
var xmlhtt
function load(str,str1)
{
xmlhtt=GetXmlHttpObject();
if (xmlhtt==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}
var url="examples/line-log-axis/index.php";
url=url+"?q="+str;
url=url+"&q1="+str1;
xmlhtt.onreadystatechange=getOutpt;
xmlhtt.open("GET",url,true);
xmlhtt.send(null);
}
function getOutpt()
{
if (xmlhtt.readyState==3||xmlhtt.readyState==2||xmlhtt.readyState==1|
|xmlhtt.readyState==0)
{
document.getElementById("apDiv1").innerHTML="Loading ";
}
if (xmlhtt.readyState==4)
{
document.getElementById("apDiv1").innerHTML=xmlhtt.responseText;
document.getElementById("apDiv1").focus();
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
I guess because highgraphs are using Jquery thats y ajax is not running them
EDITED
So what you are doing is, that you have a working chart page, and through ajax you wish to load that page into a div of another page. I don't think that will be possible, you can just do that, especially if that page has javascripts, what you are doing is just getting the generated html of the working chart page, and pasting it inside the div, this won't run the necessary javascripts for the chart generation.
Try using an iframe instead.
HTML
<iframe id="frame" />
SCRIPT
function load(str,str1)
{
$('#frame').attr('src', "examples/line-log-axis/index.php?q="+str+"&q1="+str1);
}
**OLD**
series: [{
data: JSON.parse("[" + text + "]")
}]
`text = ','`, hence a json parse error. Revisit your json building # php to correctly spit `text`

Ajax Broken in Browsers works in Android

I can run this code in Android app (using PhoneGap adn jQuery Mobile) but not on desktop browsers.
It gives me a syntax error in firebug for this line =
var TicketList = eval("(" + ajax.responseText + ")");
Here is the code
// JScript source code
// ran on body load
function doJsStuff()
{
var ajax = AJAX();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
var TicketList = eval("(" + ajax.responseText + ")");
if (TicketList.ListCount > 0) {
document.getElementById("opencount").innerHTML = TicketList.ListCount +" Open Tickets";
for (Ticket in TicketList.Tickets) {
// add stuff to DOM
//AddTicketToList(TicketList.Tickets[Ticket]);
}
}
else {
document.getElementById("opencount").innerHTML = "All Tickets Reviewed";
DisplayNoresults();
}
}
}
ajax.open("GET", "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open", true);
ajax.send(null);
//document.addEventListener("deviceready", onDeviceReady, false);
//event to check for PhoneGap
//$('ul').listview('refresh');
$('#mtickets').page();
//showVars();
}
function AJAX()
{
var xmlHttp;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
}
return xmlHttp;
}
**TicketList is a variable in the JSon that comes across like this=
{"Tickets" : [{"TicketID": "1054","Category": "N/A","SubmittedUserID": "bob.thebuilder","ShortDescription": "test question QID:16668","CreationDate": "2/16/2011 12:24:19 PM","TicketStatus": "Open","LongDescription": "Something is wrong with this question I know I hve the right answer but it keeps telling me I'm wrong"},{"TicketID": "1053","Category": "Mission Support","SubmittedUserID": "dave","ShortDescription": "Make courseware revisions","CreationDate": "2/16/2011 9:34:48 AM","TicketStatus": "Open","LongDescription": "Find help tickets generated by users for possible courseware update."}], "PageCount": "6", "ListCount": "11"}
Note about PhoneGap If you are trying to include phoengap functions in a place where the code may also be executed on in a browser make sure you only add the phone gap function with on "deviceready" or your browser will not render. Example:
function onload(){
//event to check for PhoneGap
document.addEventListener("deviceready", onDeviceReady, true);
}
...
function onDeviceReady()
{
// Now PhoneGap API ready
vibrate(90); // vib to ack pg ready
$("a").click(function(event){
vibrate(30); // add 30 sec vib to all links
});
}
My immediate response would be to use jQuery's getJSON method, since you're aready using jQuery. jQuery's AJAX provides a much broader base of browser compatibility. Also, every time you use eval(), a small baby somewhere cries.
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(TicketList){
if (TicketList.ListCount > 0) {
$("#opencount").html(TicketList.ListCount +" Open Tickets");
for (Ticket in TicketList.Tickets) {
...
}
} else {
$("#opencount").html("All Tickets Reviewed");
DisplayNoresults();
}
});
If this still doesn't work for you, ensure that the JSON being returned is valid. But please stick to this method, and don't use eval!!
SIMPLIFIED UPDATE
var url = "http://website.com/ListTicketsRequest.ashx?PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url ,function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
UPDATE USING 'DATA'
If your url becomes too long, you might begin to encounter problems. It is suggested to pass the url data via the data argument.
var url = "http://website.com/ListTicketsRequest.ashx";
var data = "PageNumber=1&PageSize=1&Status=Open";
$.getJSON(url, data, function(AnyNameYouWant){
alert(AnyNameYouWant.ListCount + " Open Tickets");
});
Looking at your code, it seems likely to me that the syntax error isn't in the code you posted, but instead is contained in the JSON object you're evaluating in ajax.responseText. Take a look at the data being returned by the AJAX request. Is it valid Javascript? Does the page you're calling return something different to desktop browsers vs mobile? Is there an error message where the JSON code should be?
Another possibility: Is your app running on website.com? If not, Firefox is probably blocking the XMLHttpRequest from functioning properly. Firefox 3 and below block cross-site AJAX requests. Firefox 3.5 seems to allow some exceptions.

Colorbox not appearing on links called through ajax

I am trying to use colorbox on a page where i have three links each of which have onclick event which call an ajax page and response text is shown in the necessary divs. everything is working fine except colorbox links. After i call the content through ajax the links are not working to appear the colorbox. Here is my code to call the colorbox which is when page is loaded working.
<p>
$(document).ready(
function()
{
$(".editchecklist").colorbox({width:"50%", height:"35%", iframe:true, onClosed:function(){ location.reload(true); } });
}
);
I tried to look for this problem but everything is related to jQuery ajax call not simple ajax call. The are advising to use .live() or rebind methods which i have no idea how and where should i use them.
here is my ajax call code:
function getxmlhttp()
{
var xmlHttp = false;
if (window.XMLHttpRequest)
{
// If IE7, Mozilla, Safari, etc: Use native object
var xmlHttp = new XMLHttpRequest();
}else
{
if (window.ActiveXObject)
{
// ...otherwise, use the ActiveX control for IE5.x and IE6
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function process_ajax2(phpPage, objID, getOrPost,clickedLink)
{
xmlhttp = getxmlhttp();
var obj = document.getElementById(objID);
if(getOrPost == "get")
{
xmlhttp.open("GET",phpPage);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('change_'+clickedLink).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
}
Please tell me how would i solve this problem?
thanking you.
if I understand your question correctly, you've loaded content into the page via ajax after pageload.
The javascript that you've got is only going to work for data that is there on page load, so what you'd need to do is use .live() which will work on elements loaded at page load and after.
(note: I don't know what page you're trying to call here - so I am assuming it is in the link href)
Something like this should work
$(function(){
$(".editchecklist").live('click',function(e){
e.preventDefault();
$.colorbox({
width:"50%",
href:$(this).attr('href'),
height:"35%",
iframe:true,
onClosed:function(){
location.reload(true);
}
});
});
});
more on jquery live http://api.jquery.com/live/

Two ajax function calls on single click

I've some folders in a div and contents of those folders are shown in tree view(when small plus button is clicked) using following code:
echo '<span class="toggle" onclick="getchildren(\''.$objectnode["fid"].'\', \'childdiv'.$objectnode["fid"].'\');" ></span>';
when folder is clicked,its contents are shown in another div,parallel to it using following code:
<span><?php echo $objectnode["object_name"]; ?></span>
Now what i want to do is, when i click on folder name,its contents should be load in div parallel to it as well as its child nodes should also be visible or expand at the same time. Any help will be appreciated
Just make two ajax calls. Ajax calls are asynchronous and you can make as many as you like. For example, you could do something like this:
function ajax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'yourpage.php', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
// Your callback code goes here
xmlhttp.responseXML; // this is the response data
}
};
xmlhttp.send(yourdatahere);
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.open('POST', 'yourpage.php', true);
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4) {
// Your callback code goes here
xmlhttp2.responseXML; // this is the response data
}
};
xmlhttp2.send(yourdatahere);
}
Call this function from your onclick function and that should do the trick. You can also nest the function calls. For example, if you're waiting on data from the first call, put the second ajax call in the callback from the first and do all of the updating. You won't need to wait for the second ajax call to return to update the DOM.
You could also make a separate ajax call for each child node, and if you want to do that for all of the child nodes, you'll have to do some recursion, such as:
function ajax(parentNode){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'yourpage.php', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
// Your callback code goes here
xmlhttp.responseXML; // this is the response data
// do stuff with responseXML
}
};
xmlhttp.send(yourdatahere);
var i;
for(i = 0; i < parentNode.childNodes.length; i++){
ajax(parentNode.childNodes[i]);
};
}
There are already plugins made for this. I know jQuery has one for it's framework. I built my own because it wasn't exactly what I wanted. I hope this helps!

Resources