xhr does not get invoked from js - javascript

i am using phonegap and trying to invoke a xhr POST on click of a button.
my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:
function fetchTags(){
console.log("Fetched url is:" + IMAGE_URL);
//var url = "http://localhost:8080/echo";
var url ="http://localhost:8080/echo";
console.log("#1");
var xhr = new XMLHttpRequest();
console.log("#2");
xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
console.log("#3");
xhr.setRequestHeader("Content-type", "application/json");
console.log("#4");
xhr.open('POST', url, true);
console.log("#5");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response);
}else{
window.alert(xhr.status);
}
};
console.log("#5");
//var msg = "{'message' : '" + IMAGE_URL + "'}";
console.log("sending request");
xhr.send(JSON.stringify({"message" : "my msg"}));
}
Button code:
<button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
The console prints:
Fetched url is:undefined
#1
#2
#3
To clarify i can see first console.log getting printed. but that's it. nothing happens after that.

just for everyone's benefit the issue was not the javascript but invoking from the phonegap using the localhost.
I was unders the assumption that phonegap will be able to access my api at localhost (not sure why had this stupid idea) but yes using the actual ip of the host machine made it work right away.

Related

How to send an API get request using JavaScript with HTML variables

I am trying to make a GET request to a web API using what is inputted in a textbox. So far I have the input value established but can't seem to figure out to send the request.
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
console.log(requestdata);
This function correctly but I can't seem to figure out the rest.
I am trying to do the following:
https://api.example.com/request?=${requestdata}
or
https://api.example.com/request/${requestdata}/test
Keep in mind that this is a static HTML site with no Node
Something like this should work to make an asynchronous GET request:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
httpGetAsync("https://api.example.com/request?=${" + requestdata + "}");
<input type="text" id="request" value="test">
If you check the developer tools > network tab you should see the GET request to the API endpoint.

make a post request in js and open its results in a new window

I have a js file, containing a folder myFunc(phone_number)
Now when this js function is called, I want to make a POST request to the URI https://pay.something.in:443/FetchPhone/ passing the json {'phone_number' : 10 digit phone no. } as input to the request
and show its output in a new window.
Can somebody tell me how do I do that?
Seems to me like you want to make a POST request with xhr.
var xhr = new XMLHttpRequest();
xhr.open('POST', "https://pay.something.in:443")
xhr.setRequestHeader("Content-type", "application/json");
xhr.send( '{"phone_number" : 4455566677 }' );
xhr.onreadystatechange = function(){
if (xhr.readyState != 4) return;
if (xhr.status != 200 && xhr.status != 304) {
alert('HTTP error ' + req.status);
return;
}
console.log(xhr.responseText);//this is your response
window.sessionStorage['response'] = xhr.responseText;
window.open('Your window');//The data is accessible through sessionStorage.
}

Why is this JSON query not working?

I am so confused at the moment, as to why this will not work.
<div id="result" style="color:red"></div>
and
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('https://www.eobot.com/api.aspx?coin=DOGE&json=true').then(function(data) {
alert('Your Json result is: ' + data.DOGE); //you can comment this, i used it to debug
result.innerText = data.DOGE; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
It's exactly the same as: http://jsfiddle.net/RamiSarieddine/HE2nY/1/ but yet that works..
Edit: For the sake of clarity, the script is supposed to take the content at the url (within the DOGE element) and display it within
<div id="result" style="color:red"></div>
I tested it and i get below error, Which means when you try to get the json from https://www.eobot.com/api.aspx?coin=DOGE&json=true , its blocked from receiving the data due to cross browser rules.
No 'Access-Control-Allow-Origin' header
How to fix it ,
You must own https://www.eobot.com and run this script on www.eobot.com , Else you cant get the json due to cross domain policy.Ask the owner to whitelist your domain in his allow-origin header.

XMLHttpRequest JavaScript not running after Open Method

I have a problem with my javascript function, I notice that the Http Post Request was not arriving at my server.. So I inserted a few alert boxes on my javascript code to see where was the problem..
Here is my javascript function:
function callService(id) {
id.innerHTML = "Clicked!";
alert("Before do XMLHttpRequest!");
var xmlhttp = new XMLHttpRequest();
alert("Before do url!");
var url = "http://this_is_an_address_valid_but_i_wont_show_you/";
alert("Before do open!");
xmlhttp.open("POST", url, true);
alert("Before do setRequestHeader!");
xmlhttp.setRequestHeader("Content-type", "application/json");
alert("Before do onreadystatechange!");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
alert("Before do parameters!");
var parameters = JSON.stringify({"Values": {"Value": 2500,"ItemNumber": "1"},"PartnerID": "S","ProdCode": "C","TC": "111","OpCode": "10"});
alert("Before do send!");
xmlhttp.send(parameters);
alert("After do send!!");
}
I notice that I don't see the alert box "Before do setRequestHeader!" , so I guess the open method of the XMLHttpRequest is not working?
Thanks alot in advance, can someone help me?
You have a cross domain issue: check this answer: How to make cross domain request.
In a few words, you can't make an AJAX call to a server if the JS file has been obtained from another one (security reasons).

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Categories

Resources