Testing Ajax using localhost - javascript

I am trying to test a simple Ajax script using Javascript and I'm not receiving a response. The PHP script is placed in the htdocs folder of the local server and the HTML page that includes the Ajax calls is placed on my desktop. A readyState of 4 is received from the server but the status returned is 0, not 200.
The error generated on Firefox state:
NS_ERROR_DOM_BAD_URI: Access to restricted URI denied.
Here is the section of code responsible for calling the Ajax object:
var myRequest = getXMLHttpRequest();
function callAjax() {
var url = "localhost/clock.php";
var myRandom = parseInt(Math.random()*99999999);
myRequest. open("GET", url + "?rand=" + myRandom, true);
myRequest.onreadystatechange = responseAjax;
myRequest.send(null);
}
function responseAjax() {
if(myRequest.readyState == 4) {
if(myRequest.status == 200) {
var now = new Date();
var localTime = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
var serverTime = myRequest.responseText;
document.getElementById("clock").innerHTML = "Server: " + serverTime + "<br />Local: " + localTime;
} else {
alert("An error has occurred: " + myRequest.statusText);
}
}
}
Can anyone offer insight to my problem?
OSX 10.8.5
MAMP version 2.1.3

You say your file is on the desktop. You cannot open a local file ( file:// ) and do ajax. You need to access the file through your Apache server ( http:// ).

Related

Why does the Resources Received change so frequently for same URL (page.open(url))

I am currently working on fetching/scraping all the images being received on requesting a URL.
The problem i am facing is the response changes after few tries or is very inconsistent even for the same URL using the phantomjs.
I have tried clearing cache multiple times and at different location in my code but the the request numbers dont appear to be the same.
o/p
1st call to URL
19 images and total off 49 responses from server
2nd call
14 images and 48 responses from server
3rd call
14 images and 38 responses from server
Output for execution twice
phantomjs-2.1.1-windows
running a java-script code using the phantomjs command
I am very new to Javascript, i have manged to write the following till now
var page = require('webpage').create();
var fs = require('fs');
var url = "https://..........";
page.settings.clearMemoryCaches = true;
page.clearMemoryCache();
page.clearCookies();
page.viewportSize = {width: 1280, height: 1024};
var imageCounter = 0;
var responseCounter = 0;
page.open(url, function (status) {
console.log(status + '*/*/*/*/*/*/**/*/*/*/*/*/*/*/*/*/*/*/*/*/')
if(status=='success'){
console.log('The entire page is loaded.............################');
console.log('\n' + imageCounter + '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n');
console.log('\n' + responseCounter + '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n');
imageCounter = 0;
page.clearMemoryCache();
page.clearCookies();
page.close();
phantom.exit();
}
});
page.onResourceReceived = function(response) {
if(response.stage == "start"){
responseCounter++;
var respType = response.contentType;
if(respType.indexOf("image")==0){
imageCounter++;
//console.log('Content-Type : ' + response.contentType)
//console.log('Status : ' + response.status)
//console.log('Image Size in byte : ' + response.bodySize)
//console.log('Image Url : ' + response.url)
//console.log('\n');
console.log(imageCounter + '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n');
}
}
};
I want to get consistent response for the images at least, I am really confused how does phantom cache this kind of resources on second attempt.

how to show an error when in appbrowser does not load error phonegap

i am developing an application and loading an hosted application using the inapp browser plugin cordova-plugin-inappbrowser
I have gotten most of the functionalities to work but i am unable to get the part of loading an error message when he url does not load, it dosent just work and shows me an error message of the url where i have hosted my application instead.
Which could be embarrassing.
please i need help on this
This is what am working with below thanks for ur potential responses
// my child browser code, the main source of my app content
function fire(){
var ref = cordova.InAppBrowser.open('http://####################', '_blank', 'location=no,zoom=no,hardwareback=yes,clearsessioncache=yes,clearcache=no');
var myCallback = function(event) { alert(event.url); }
ref.addEventListener('loadstart', inAppBrowserbLoadStart);
ref.addEventListener('loadstop', inAppBrowserbLoadStop);
ref.addEventListener('loaderror', loadErrorCallBack);
ref.addEventListener('exit', inAppBrowserbClose);
}
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage =
"alert('Sorry we cannot open that page. Message from the server is : "
+ params.message + "');"
inAppBrowserRef.executeScript({ code: scriptErrorMesssage }, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function executeScriptCallBack(params) {
if (params[0] == null) {
$('#status-message').text(
"Sorry we couldn't open that page. Message from the server is : '"
+ params.message + "'");
}
}
Your code is generally fine, but you have no control over the title of the alert() function. You can use some other techniques to display the error message. For example, you can use a div:
function loadErrorCallBack(params) {
$('#status-message').text("");
var scriptErrorMesssage = createMsg('Sorry we cannot open that page. Message from the server is: '
+ params.message);
inAppBrowserRef.executeScript({
code: scriptErrorMesssage
}, executeScriptCallBack);
inAppBrowserRef.close();
inAppBrowserRef = undefined;
}
function createMsg(msg) {
return 'var div = document.createElement("div");'
+ 'div.style.position = "absolute";'
+ 'div.style.top = "50%";'
+ 'div.style.left = "50%";'
+ 'div.style.width = "100px";'
+ 'div.style.height = "100px";'
+ 'div.style.color = "#f00";'
+ 'div.innerHTML = "' + msg + '";'
+ 'document.appendChild(div);'
}

PhantomJS Issue with Loading Webpage: "Connection closed"'

I'm working with PhantomJS and everything that I've done works fine, but I don't know what happened bit time ago. The URL doesn't open in PhantomJS. The URL is domain and the code is as follows:
var page = require('webpage').create(),fs = require('fs'), args=require('system').args;
// var url = 'http://fotogena.co';
var url = 'https://www.procuraduria.gov.co/CertWEB/Certificado.aspx?tpo=1';
page.viewportSize = { width: 400, height: 400 };
page.open(url, function (status) {
if(status==='success'){
setTimeout(loadScripts, 1500)
}else
console.log(
"Error opening url \"" + page.reason_url
+ "\": " + page.reason
);
});
page.onResourceError = function(resourceError) {
console.error('-----',resourceError.url + ': ' + resourceError.errorString, 'faber acá toy');
phantom.exit(1);
};
function loadScripts(){
setTimeout(function(){
page.render('./probandoAntecedentes.jpg')
phantom.exit(1);
},1000)
}
The console displays the following:
https://www.procuraduria.gov.co/CertWEB/Certificado.aspx?tpo=1: Connection closed
I searched for possible solutions and put --ssl-protocol=any and other options, but they didn't work.
I'm using PhantomJS 2.1.1

Phantomjs not loading the correct url inside onResourceRequested

I have a simple script based off Phantomjs's Network Monitoring example that tries to log all the requests and the response headers associated with a particular website:
"use strict";
var page = require('webpage').create(),
system = require('system'),
address;
if (system.args.length === 1) {
console.log('Usage: getRequests.js <some URL>');
phantom.exit(1);
} else {
address = system.args[1];
console.log('The url entered is ' + address + '\n')
page.onResourceReceived = function(response) {
console.log('Received Request: ' + JSON.stringify(response.headers, undefined, 4) + '\n');
};
page.onResourceRequested = function (req) {
console.log('Request URL ' + JSON.stringify(req.url, undefined, 4) + "\n");
}
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.open(address);
}
However, when I try to run it, using ./phantomjs getRequests.js www.google.com (or any other webpage), it gives the error:
The url entered is www.google.com
Request URL "file:///home/myusername/scripts/www.google.com"
Unable to load resource (#1URL:file:///home/myusername/scripts/www.google.com)
Error code: 203. Description: Error opening /home/myusername/scripts/www.google.com: No such file or directory
Received Request: []
Basically, the url that I am entering on the terminal is being prepended with the path of the script file. The input that I am getting inside the address variable is perfectly fine i.e. google.com
Could anyone please help with this issue? I cannot understand why phantomjs maybe doing this. I am running Ubuntu 14.04 on VirtualBox. And the script was running fine before when I was just trying to output the requests for a particular page.
Thanks.
You'll probably laugh, but the correct way to use the script is
./phantomjs getRequests.js http://www.google.com

xhr response: connection closed

I wrote a Flickr search engine that makes a call to either a public feed or a FlickrApi depending on a selected drop down box.
examples of the JSONP function calls that are returned:
a) jsonFlickrApi({"photos":{"page":1, "pages":201, "perpage":100, "total":"20042", "photo":[{"id":"5101738723"...
b) jsonFlickrFeed({ "title": "Recent Uploads tagged red","link": "http://www.flickr.com/photos/tags/red/","description": "", ....
the strange thing is that in my local install (xampp) both work fine and i get images back BUT when i host the exact same code on the above domain then the jsonFlickrApi doesn't work. What i notice (by looking at Firebug) is that for the jsonFlickrApi the response Header says Connection close
Also, Firebug doesn't show me a Response tab when i submit a request to the jsonFlickrApi
here is the code:
function makeCall(uri)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "jsonget.php?url="+uri, true);
xmlhttp.send();
}
function jsonFlickrApi(response)
{
var data= response.photos.photo ;
var output = "";
output += "<img src=http://farm" + data[4].farm + ".static.flickr.com/" + data[1].server + "/" + data[4].id + "_" + data[4].secret + ".jpg>";
document.getElementById("cell-0").innerHTML = output ;
}
//Public Feed
function jsonFlickrFeed(response)
{
var data= response.items[0].media.m ;
alert(data);
var output = "";
output += "<img src=" + data+ ">";
document.getElementById("cell-0").innerHTML = output ;
}
function callback()
{
//console.log("Ready State: " + xmlhttp.readyState + "\nStatus" + xmlhttp.status);
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var jsonResponse = xmlhttp.responseText;
jsonResponse = eval(jsonResponse);
}
}
examples of calls:
a)
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
b)
http://api.flickr.com/services/feeds/photos_public.gne?tags=red&format=json&timestamp=1339190039407
Question: why does my connection close? why is it working on localhost and not on the actual domain?
Looking at the HTTP response headers of
http://flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
I get a 302 with location
http://www.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=red&content_type=1&is_getty=true&text=red&format=json&timestamp=1339189838017
So, what flicker wants to tell you is "use www.flicker.com instead of flicker.com!". With this URL I get content.

Categories

Resources