I'm developing an app in PhoneGap+dreamweaver cs5.5, who makes a call to a handler (.ashx) and returns a JSON string. I do the following:
function appReady(){
var ajax = new XMLHttpRequest();
ajax.open("GET","https://xxxx.xxxxx.com/xxxx/xxxx.ashx?method=GetUser&email=xxx#xxxx.com&pwd=123456",false);
ajax.send();
ajax.onreadystatechange=function(){
if(ajax.readyState == 4) {//Request complete !!
if (ajax.status == 200 || ajax.status == 0) { // OK response
alert(ajax.responseText);
document.getElementById('main').innerHTML = ajax.responseText;
}
}
}
}
When I running the app on the iphone emulator, I recover the json string responseText, but this comes empty on android emulator. In iphone the status returned is 200 but in android is 0.
if the problem was the coss-domain request, wouldn't work on any platform right?
I don't understand why the example of the wiki: http://wiki.phonegap.com/w/page/42450600/PhoneGap% 20Ajax% 20Sample
works correctly in two platforms and mine only in iphone ...
Check for cross-domain scripting issues. I did almost the same thing, except my URL was actually located on the same domain. It worked fine on Android and on a PC, but the iphone refused to function. When I changed from 'https://whatever.whatever.com/foo.asp' to just foo.asp - it worked!
var rootpath;
rootpath = "https://the.same.dam.place/foo.asp"; // did not work!
rootpath = "foo.asp"; // shortening it worked.
function read_foo(whatever)
{
var url = rootpath + "?whatever=" + whatever;
xmlHttp = GetXmlHttpObject(stateChanged);
xmlHttp.open("GET", url , true);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
var return_place = document.getElementById('return_place');
var thetext = xmlHttp.responseText;
return_place.innerHTML= thetext;
}
}
also see:
Empty responseText from XMLHttpRequest
Related
The data that I want to get is from API that is only return XML format.
When using IE the request is send and I get beck a response and all is fine. But when I try to use Chrome same request is in pending.
Also I have try the same code to call some open API on internet for testing that return .JSON and the same code is working on Chrome. So what am I doing wrong ?
var req = null;
req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
alert("Hi")
}
};
req.open("GET", "LINK" ,false);
req.send(null);
I'm running a Heroku server and I'm trying to change the innerHTML on my website to display certain statistics gathered from an endpoint on the server:
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = processRequest;
var element = document.getElementById('change');
element.innerHTML = xhr.valueinJSON;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
alert(response.ip);
}
}
My script tag contains the above and although the endpoint works properly in Postman, the JSON is always null. Any suggestions?
I'm not sure if valueinJSON is from an API I'm not familiar with, but I can't find a reference to it. Either way, you need to change your innerHTML in the async function like this:
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var element = document.getElementById('change');
element.innerHTML = response
}
You are trying to set the innerHTML before the browser has a chance to download it.
This assumes there is not a CORS issue. You should check your browser's console to make sure there are not errors.
I have this JavaScript function which aims to insert a keyword in a named graph which belongs to the project Dataset.
function insert(keyword) {
var query = "INSERT DATA {GRAPH <http://test1> {<subj> <pred>'" + keyword + "'. }}";
var endpoint = "http://localhost:3030/project/update";
sparqlQueryJson(query, endpoint, showResults, true);
}
I have executed Jena Fuseki with the --update option. The sparqlQueryJson function is as follows:
function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
var querypart = "query=" + escape(queryStr);
// Get our HTTP request object.
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// Code for older versions of IE, like IE6 and before.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Perhaps your browser does not support XMLHttpRequests?');
}
// Set up a POST with JSON result format.
xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
// Set up callback to get the response asynchronously.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// Process the results
callback(xmlhttp.responseText);
} else {
// Some kind of error occurred.
alert("Sparql query error: " + xmlhttp.status + " " + xmlhttp.responseText);
}
}
};
xmlhttp.send(querypart);
};
The showResults function is, in my opinion, not very important here, since it takes the results of the query and show them in HTML.
I followed what is discussed here and here, executing the query using the http://localhost:3030/project/update. The thing is that if I execute the same query on top of the local Fuseki server with the same endpoint url by using the web, it works, but from the JavaScript code, it raises the error:
"SPARQL query error: 400 Error 400: SPARQL Update: No 'update=' parameter".
I'm using Ubuntu 16.04 and Jena Fuseki - version 2.4.1.
To solve this problem the =query parameter has to be changed to =update. In addition, a parameter with the type of the query has to be handled, i.e., update or query.
if(type==="update"){
var querypart = "update=" + escape(queryStr);
}else if(type === "query"){
var querypart = "query=" + escape(queryStr);
}
...
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if(type==="query"){
xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
}
This is my HTML text:
<input type="text" class="resizedsearch" name="searchdb">
<button id="submit" onclick="ajaxCall()">Search!</button>
This is Javascript:
ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
}
And this is where I am trying to display the response that I am receiving from the PHP file:
<b><font size="24" face="Cambria"><p id="democity"></p></font></b>
<font size="6" face="Cambria"><p id="demodes"></p></font>
</br>
The output of the PHP file is stored in $outp and it is in the JSON format.
Any help appreciated. Thank you.
!!UPDATE!!
function ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
}
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
This is how the improvised code looks. Still not working.
Example by FactoryAidan is not going to work as it violates Same Origin Policy (unless you'll run the code in browser console on Google page). Try replacing http://www.google.com with your local address. I tested the code with a little modification and it works, or at least gives alert, so the function is called. Here's it is:
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080"; /* but make sure the url is accessible and of same origin */
xmlhttp.onload=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here');
}
Your code update after my first answer looks like it was done in haste and I think makes the question a little harder. The .open() and .send() methods ended up inside your .onreadystatechange function definition but they need to be outside. Your first one didn't have those placement issues. The code I wrote below has your exact building blocks but with no placement issues so you should be able to follow along with how it matches your example code. I also tested it and it sucessfully sends and receives data back and successfully calls the myFunction() callback function.
Nonetheless, I took your code and rewrote it a bit. If you get an alert('') message when you run it, that means that your xml request worked perfectly. If you don't see an alert('') message. It means your xml request is returning a http 404 error, which means your request URL is bad. Try changing your request URL to something you know won't give you a 404 error, like 'http://www.google.com'. If it works and you get the alert message, then the only problem is that your localhost:8080 url is a bad url.
Also, in your myFunction callback function, javascript treats line-breaks as the end of a line of code. So you must write assignments that use an '=' sign on the same line with no line-breaks. Due to this javascrit principle, you also don't need a semicolon ';' at the end of a single line like you would in PHP script.
Finally, a big cause of errors can be the JSON.parse() call. The data received MUST be a valid json string. So if the URL you call returns anything other than pure json... your myFunction() callback function will break on the JSON.parse() command.
Lastly, if there is an error in your myFunction() callback function, your browser inspector will not report it in a useful way and will instead throw an error that points to your xmlhttp.onreadystatechange=function(){} as being the culprit because that is where the browser thinks the error resides (being the calling function), even though the real error is in your myFunction() callback function. Using my edit of your ajaxCall(){...} code and with a valid url, you can be positive that the ajax call works and any errors you have are in your myFunction() callback function.
Lastly again, You have to be careful in your callback function because there are so many things that could break it. For example, document.getElementById() will cause an error if no html element exists on your web-page with the id you provided. Also, if the JSON you received back from the ajax call is missing any properties you mentioned like (city or latitude) it is likely that the innerHTML will be set to 'undefined'. But some browsers may treat the missing json properties as an error instead of just saying they are 'undefined' when you try to call them.
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://www.google.com";
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here')
/*
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML = obj.city
document.getElementById("demodes").innerHTML = obj.description
document.getElementById("latlon").innerHTML = obj.latitude + "," + obj.longitude
*/
}
currently i using this code in phonegap application
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://192.168.1.19:8080/searchMobile?categoryRequest=true", true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {alert(xmlhttp.status);
if (xmlhttp.readyState == 4) {
var responseObject = eval("(" + xmlhttp.responseText + ")");
var results = responseObject.result;
if (results != null)
{
var resLength = results.length;
category.length = category.length + resLength;
for ( var i = 0; i < resLength; i++)
{
category.options[category.length - (resLength - i)].innerHTML = results[i].categoryName;
$(category).selectmenu("refresh");
}
}
}
this code is working in android but when i run this code on iphone it gives status 0 means doesn't work.
how can i overcome this problem
many thanks.
First as #Raymond Camden said make sure your url is white listed in the .plist. Second it is perfectly normal for you to get a status of 0 when doing AJAX from the file:// protocol. Webkit will set the status to 0 because you are doing a cross domain request which in a web browser would be blocked but in a web view, like PhoneGap uses, is perfectly okay. So in this case 0 == 200. Third get rid of eval, if you are returning JSON data use JSON.parse(xmlhttp.responseText) as it is much safer.
Try adding the URL to the whitelist.