I am trying to retrieve information from a javascript file in my jQuery mobile website. Ajax is enabled by default, yet when I try xmlHttpRequest.send(), the responseText is the source code for the page rather than a json structure. The initialize() function is run at pageinit, so my thinking is that the json it is retrieving should exist when called. Also, initialize() works fine on the non-mobile variant of the site so I think it has something to do with how JQM handles ajax requests. Thanks in advance for any assistance.
<!DOCTYPE html>
<html>
<head>
var xmlHttpRequest;
var json;
<script type="text/javascript">
function initialize()
{
xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() :
new ActiveXObject("Msxml2.XMLHTTP");
if (xmlHttpRequest == null)
return;
xmlHttpRequest.open("GET", "pick.js", false);
xmlHttpRequest.send();
json = eval('('+ xmlHttpRequest.responseText +')');
}
</script>
......
</head>
<body>
<div data-role="page" id="map-page">
<script type="text/javascript">
$('#map-page').live('pageinit',function(){
initialize();
});
</script>
.....
</div>
</body>
</html>
Since you're using jQuery Mobile (and thusly, jQuery), you should consider using jQuery.ajax -- it handles all of the 'hard stuff' like creating XHR object for you.
For your situation your code would look like this:
function initialize() {
$.get("pick.js", function(data, status, jqXHR) {
//when the call succeeds, do something with the 'data' param
console.log(data);
}, "script");
}
Related
How can I add a busy indicator before the Ajax popup appears on screen? I have been trying to follow several examples, but they are overly complex and very confusing for what seems should be an easy fix. Can anyone please help? Very new to Ajax. Thank you!
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
alert(response);
});
});
});
</script>
</head>
<body>
<input type="submit" class="button" name="Start" value="Start" />
</body>
</html>
You have to add the indicator when starting the ajax call and remove it when the call returns.
But you should fix your html (input element is only valid inside a form tag) and then you have to prevent the form submission. If you follow this rules your code looks like this:
$(document).ready(function(){
$('.button').click(function(evt){
// preventing the form submission
evt.preventDefault();
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
// add indicator here (before the ajax request starts)
var $indicator = $('<div>Ajax in progress...</div>').appendTo('body');
$.post(ajaxurl, data, function (response) {
// removing the indicator inside the success handler of the ajax call.
$indicator.remove();
alert(response);
});
});
});
I want to make a specific component for showing loading icon when the browser waits to load data from json. Is there any possible way to do it by using a service ??
html :
<html ng-app="app">
<head>
<title> ERP </title>
</head>
<body >
<div ng-controller="data"><span class="loading" ng-show="loader"><img src="ajax-loader.gif"></span>
<table>
<tr><td>{{data1}}</td><td>{{data1}}</td><td>{{data1}}</td></tr>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script type="text/javascript" src="ctrl.js"></script>
</body>
</html>
js :
var app = angular.module('app',[]);
app.controller('data', ['$scope','$http',function($scope,$http){
$scope.loader = null ;
if($scope.loader == null )
{
$scope.loader = true ;
}
$http.get('events.json').
success(function(data) {
$scope.loader = false ;
console.log(data);
$scope.data1 = data ;
console.log($scope.data1);
}).
error(function(data, status, headers, config) {
});
}]);
You can wrap the original $http to provide a customizedHttp service. in this service, provide the same interface with $http. when sending GET request to the server, the customizedHttp broadcast an event to show the loading flag. and after receiving response, broadcast another event to hide the loading flag.
to control the flag, you'd better to write a directive.
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript" src="Chat_Box_Files/Script_Files/AJAX.js"></script>
</head>
// JavaScript Document
$(document).ready(function(){
// load index page when the page loads
Load_ajax_page("http://betaserver.bioprotege-inc.net/chat_selector/Chat_Box_Files/Script_Files/Applet_Files/Index.html");
$("#ChatMaster").click(function(){
Load_ajax_page("#");
});
});
function Load_ajax_page(url){
//before we make a ajax request we have to show the loading image
$("#Applets").html('<center>Loading... Please Wait...</center>');
//this is a jquery method to make a ajax request
$.post(url,"",function (data){
//this is the place where the data is returned by the request
//remove loading and add the data
$("#Applets").html(data);
});
}
<div id="Applets">
</div>
http://jsfiddle.net/N278r/
here is my fiddle of it all in action, but it wont display the content from the html file, it used to idk what I have done wrong?
It looks like you are using ASP.NET on the server. You can add the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
I'm still relatively new to AJAX and am trying to figure out why my simple test is not working. From what I read AJAX will not work under one domain, and other words pop up like cross-site and remote server. Anyways my problem is is that I'm not sure if my code is wrong or simply what I'm trying to do is impossible. I created a simple ajax request to submit data when I click on the button. Here is the code for the first script.
<html>
<head>
<script type="text/javascript" >
function load(thediv, thefile) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" onclick="load('adiv', 'hello.php');">
<div id="adiv"></div>
</body>
</html>
Here is the code for the file hello.php
<?php
echo 'aaa';
?>
AJAX is just an http request done in the background. But yes, there are security restrictions that prevent you doing a normal ajax request to any arbitrary server.
What your code is missing is actually setting the URL that you're placing the request to. You've got hello.php as a parameter to your load() function, but you never actually USE it. So you're doing an AJAX request to... "nowhere".
I have a very simple javascript class that does an ajax call to a web service of mine via jquery. It returns the data successfully, but I am unable to retrieve it via a variable I set the data to. I don't think it is a matter of the ajax call being asynchronous or not because I have set up event handlers for all the ajax events, but some of them do not fire. I have no idea what is wrong. Here is the complete code:
Javascript:
function testClass(){
this.returnData = "";
this.FireAjax = function(){
$.getJSON("http://localhost/mywebapp/webservices/service.asmx/Initialize?userID=12&jsoncallback=?",
function(data){
this.returnData = data.d;
alert(data.d);
}
);
}
}
HTML page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://localhost/mywebapp/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="testClass.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var obj = new testClass();
$("#debug").ajaxError(function(event, request, settings){
$(this).append("<b>Ajax Error!</b><br />"); //this does not fire
});
$("#debug").ajaxSend(function(evt, request, settings){
$(this).append("<b>Ajax Send!</b><br />"); //this does not fire!?
});
$("#debug").ajaxStop(function(){
$(this).append("<b>Ajax Stopped</b><br />"); //this fires
});
$("#debug").ajaxComplete(function(event,request, settings){
$(this).append("<b>Ajax Completed!</b><br />"); //this fires
$(this).append("<h2>" + obj.returnData + "</h2>"); //this returns an empty string!!!!!!
});
$("#debug").ajaxSuccess(function(evt, request, settings){
$(this).append("<b>Ajax Successful!</b><br />"); //this fires
});
$("#debug").ajaxStart(function(){
$(this).append("<b>Ajax Started!</b><br />"); //this fires
});
obj.FireAjax();
});
</script>
</head>
<body>
<div id="debug">
</div>
</body>
</html>
Additional Info:
If I remove the complete event in my html page and place the call to obj.returnData in my stop event (thinking that perhaps my html complete event overwrites my testClass complete function), i get the same results.
Your problem is here:
this.returnData = data.d;
this inside the anonymous function refers to the jQuery Options object, not the instance of your object.
Try this:
function testClass(){
this.returnData = "";
var that = this;
this.FireAjax = function(){
$.getJSON("http://localhost/mywebapp/webservices/service.asmx/Initialize?userID=12&jsoncallback=?",
function(data){
that.returnData = data.d;
alert(data.d);
}
);
}
}