So I have a simple WebAPI Controller with...
[HttpGet]
public string Demo()
{
System.Diagnostics.Debug.Print("API Demo call hit " + DateTime.Now.ToString());
return "Got Here";
}
Because of the Debug output, I can tell that it is actually getting called from my javascript. So I know that my script is at least connecting. I also know that if I put a break on the line.. the script (html page) does pause and wait until I let the code continue. So they are talking, but I have 2 issues...
1) Every time I make a send call, I get the script error "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:64769/api/demo'" ... even though I know it is talking to it. But I did notice that if I do NOT trap for errors, the script fails on the "Send" line and doesn't continue.
2) However, with the error trap, the script does continue (as expected) but the XMLHttpRequest doesn't have my return. (e.g. responseText is blank).. pretty much every single property of the object is blank or null.
So I think my response is empty because there is a problem with the "send". However because it is actually calling my Controller and waiting on it to run, I'm lost as to what the problem is?
Here is my script...
function CallWebAPI()
{
var displayResults = document.getElementById('responseDetails');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:64769/api/demo", false);
try
{
xmlhttp.send();
}
catch(err)
{
displayResults.innerHTML += err + "<br />";
}
displayResults.innerHTML += "The Results...<br />";
for (var key in xmlhttp)
{
displayResults.innerHTML += key + "---" + xmlhttp[key] + "<br />";
}
}
All,
So after an entire day and half of messing around, finally figured it out. I guess I was running an HTML file from my desktop, and my Web Service was running on http://localhost:64769.
This is one of those cross domain things. When using an HTTP client in .NET, I did not have to deal with this.. but once I tried to use a client other than .NET, my Web service actually responded.. but the client Browser would not accept the response.
The fix was to change my api service to...
[HttpGet]
public HttpResponseMessage Demo()
{
string myReturnMessage = "API Demo call hit " + DateTime.Now.ToString();
System.Diagnostics.Debug.Print(myReturnMessage);
HttpResponseMessage myReturn = this.Request.CreateResponse(System.Net.HttpStatusCode.OK, myReturnMessage);
//This was the KEY!!!!
myReturn.Headers.Add("Access-Control-Allow-Origin", "*");
return myReturn;
}
Related
I have this java script code on my website which gets executed when someone subscribes to my newsletter. It is basically nothing but post request. This is the piece of code.
function es_submit_request(url, parameters, es_widget_form) {
http_req = false;
http_req.onreadystatechange = function() {eemail_submitresult(es_widget_form)}; // Passing the form to the submit request
http_req.open('POST', url, true);
http_req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_req.send(parameters);
}
Is is possible to call this post method from my android application code to subscribe someone to my newsletter?
I have tried this code here but it is not working.
When I debug my js code, variable values are coming as
parameters = "es_email=fgnfg#dgd.com&es_name=&es_group=×tamp=&action=0.9901232281510463"
url = "http://thetechguru.in/?es=subscribe"
I would highly appreciate if someone could help me with the code for this. I rather not use any library for this because I don't want overhead for such small thing. (for only one network call in my app)
This is the piece of code which I am trying but it is not working.
String urlString = "http://www.thetechguru.in/?es=subscribe&es_email=fsdsf#dgd.com&es_name=&es_group=×tamp=&action=0.9901232281510463";
String resultToDisplay = "";
InputStream in = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (Exception e) {
System.out.println(e.getMessage());
return e.getMessage();
}
try {
resultToDisplay = in.toString();//IOUtils.toString(in, "UTF-8");
//to [convert][1] byte stream to a string
Log.v("Response",resultToDisplay);
} catch (Exception e) {
e.printStackTrace();
}
Code executes, but nothing happens, email id is not added in list
What does you Application Manifest file look like? If your application doesn't have permission to access the internet, it won't. Try adding <uses-permission android:name="android.permission.INTERNET" /> to your AndroidMainfest.xml file (inside the <manifest> tag, but before the <application> tag.
Does anything show up in your log (log.v will only show if set to verbose)? If so, please share what it shows. Log guide
Failing that, is the es_email=fsdsf#dgd.com email already in the list? Make sure you're updating the es_email parameter of your URLstring on the button's
I have finally solved the issue. Even though I was using proper code sending POST request, I was unable to subscribe the email id. I checked the HTTP response for the request and found that it was returning error "unexpected-error". I checked in server code and there was this condition of checking HTTP_REFERER in php code. So did a little research and added REFERER in my java request and voila, success!
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//Set to POST
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setDoInput(true);
//Added referer
connection.addRequestProperty("REFERER", "http://thetechguru.in");
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.setReadTimeout(10000);
Writer writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(query);
writer.flush();
writer.close();
I hope it helps someone
Note: I am aware that json/jquery appears to be the preferred way of doing things at the moment. Nevertheless, I am using just plain old ajax without json/jquery.
I have set my website up so that there are no php calls in the index page. Instead, I load scripts which handle most link clicks via ajax calls back to the server. Theoretically, the server returns the response text, and then the javascript on readystatechange function (set to ajax_response()) inserts the response text directly into the div container with id="innercontent".
Here is the code for my main javascript file:
function ajax()
{
try{ var request = new XMLHttpRequest()}
catch(e1){
try{ request = new ActiveXObject("Msxml2.XMLHTTP") }
catch(e2){
try{ request = new ActiveXObject("Microsoft.XMLHTTP") }
catch(e3){ request = false }
}
} return request
}
function ajax_response()
{
if(this.readyState == 4){
if(this.status == 200){
if(this.responseText != null){
document.getElementById('innercontent').innerHTML = this.responseText
} else alert("Ajax error: No data received")
} else alert("Ajax error: " + this.statusText)
}
}
function fetch_document(opcode)
{
params = "opcode=" + opcode
request = new ajax();
request.open("POST", "/site-php/fetch_document.php", true)
// request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = ajax_response()
request.send(params)
}
function fetch_comic(series, page_number)
{
params = "series=" + series + "&page_number=" + page_number
request = new ajax();
request.open("POST", "/site-php/fetch_comic.php", true)
// request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
// request.setRequestHeader("Content-length", params.length)
request.setRequestHeader("Connection", "close")
request.onreadystatechange = ajax_response()
request.send(params)
}
There doesn't appear to be any syntax errors in the javascript, so I thought maybe that the problem was on the server side. But no errors are logged in /var/log/error_log.
Here is the code for my php functions:
<?php
require_once "kolodruid.php";
require_once "login.php";
if(isset($_POST['series']) && isset($_POST['page_number'])){
$series = $_POST['series'];
$page_number = $_POST['page_number'];
}
$mysql_db = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_select_db("webcomics");
mysql_close($mysql_db);
$fd = $docroot . "test.html";
$msg = file_get_contents($fd);
echo $msg;
?>
Note that the actual functionality of this function is to fetch webcomic information from a database. In the process of trying to figure out what has gone wrong, however, I ended up simplifying the function to try to see if just a simple echo statement would work.
also:
<?php
require_once "kolodruid.php";
$opcode = $_POST['opcode'];
switch($opcode){
case "ABOUT":
echo file_get_contents("about.html");
break;
default:
echo file_get_contents("whoops.html");
break;
}
?>
When I look at the firefox console network tab, clicking on the links "webcomic" generates green lights all the way. I check to see if the parameters tab has any data, and it does. The response tab, however, doesn't contain anything.
I've checked that all the files are reachable and in places that the server has access to. I also took out the setrequestheader() functions in the javascript, as it seems that was causing a fatal error. I then re-enabld the close connection setrequestheader() to see if maybe I actually still had to set that one manually. It seems that it didn't generate a fatal error, so I didn't comment it back out.
I've checked the php code for syntax errors, and also checked the javascript code for syntax errors. Both come out clean. I've restarted my server several times (it's localhost), and have also restarted my mysql database server out of desperation.
At this point, the whole enterprise had devolved into just making minor edits in the desperate hope that SOMETHING gives a clue as to what is going on. I have changed the asynchronous calls to synchronous calls to see if that maybe was the problem, but to no avail. (Thus, I rechanged them back to asynchronous calls).
I feel like it's something really stupid and/or obvious, but I've been pouring over the code for hours, and am afraid I can't see the forest for the trees by now. Please help!
Thank you for reading this. I'm aware that Javascript questions are pretty common, but I've been reading question and answer sites for hours, too. D:
In case it matters, I'm using Apache version 2.4.6
Thank you for you help!
It turned out to be something mind-blowingly obvious after all. I was calling the function ajax_response() and assigning the value to onreadystatechange. Removing the parenthesis after ajax_response produced the desired behavior.
First off, thanks for taking the time to read.
I'm trying to delve into ASP.NET MVC at the moment, however i currently have no wish to use any type of JavaScript framework, so please, don't tell me how much easier it would be etc, in your answer.
I currently have a Javascript function that successfully makes an AJAX call, however i am struggling to understand why no values are being returned from the request.
The function is as follows.
function ajaxRequestUser(num) {
var ajax;
try {
ajax = new XMLHttpRequest();
} catch(e) {
try {
ajax = new ActiveXObject(Msxml2.XMLHTTP);
} catch(e){
alert('old browser');
}
}
ajax.readystatechange = function () {
if (ajax.readyState == 4) {
var queryResult = ajax.responseText;
if (!queryResult) {
alert('No Information.');
} else {
alert(queryResult);
}
}
}
var requestString = "?user="+num;
ajax.open("GET", "/Users/GetUser" + requestString, true);
ajax.send(null);
}
The function is called via a separate function that simply does some UI modifications to allow for the display of the data.
The alerts are there at this point, because i was not receiving any data back from the call and i was testing to see if that part of the code was being hit at all (Don't go into the differences between Synchronous and Asynchronous.). No matter how long i waited the data being returned was not being returned, after breaking through the actual server side c#, i saw the data being sent back, but it was just never being received. Is there something in the code that was done wrong? Or am i going about receiving the inbound data in the wrong way?
I have found the issue related to my code, and it is solely an error based around the declaration of my ajax.event where the event is onreadystatechange as opposed to readystatechange
I'm trying to build a Google query string, make a request to that page, scrape the HTML, and parse it in a Chrome extension, which is JavaScript. So I have the following code:
var url = "https://www.google.com/search?#q=" + artist + "+" + title;
searchGoogleSampleInformation(url);
function searchGoogleSampleInformation(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4)
{
return parseGoogleInformation(xhr.responseText, url);
}
}
xhr.send();
}
function parseGoogleInformation(search_results, url)
{
var link = $(".srg li.g:eq(0) .r a", search_results).attr('href');
}
The parse method just grabs the url of the first search result (which is not want I'll end up doing, but just to test that the HTTP Request was working). But link is undefined after that line. Then I used alert(url) and verified that my query string was being built correctly; I copied it from the alert window and pasted into another tab, and it pulled up the results as expected. Then I opened a new window with search_results, and it appeared to be Google's regular homepage with no search at all. I thought that problem might be occurring because of the asynchrony of the xhr.open call, but flipping that didn't help either. Am I missing something obvious?
It's because "https://www.google.com/search?#q=" + artist + "+" + title initially has no search results in the content. Google renders the page initially with no results and then dynamically loads the results via JavaScript. Since you are just fetching the HTML of the page and processing it the JavaScript in the HTML never gets executed.
You are making a cross domain Ajax call, which is not allowed by default. You cannot make a cross domain call unless the server supports it and you pass the appropriate headers.
However, as you mentioned you are building a Chrome extension, it is possible by adding a few fields in the manifest file: https://developer.chrome.com/extensions/xhr#requesting-permission
Edit: Maybe I made the question more complex than it should. My questions is this: How do you make API calls to a server from JS.
I have to create a very simple client that makes GET and POST calls to our server and parses the returned XML. I am writing this in JavaScript, problem is I don't know how to program in JS (started to look into this just this morning)!
As n initial test, I am trying to ping to the Twitter API, here's the function that gets called when user enters the URL http://api.twitter.com/1/users/lookup.xml and hits the submit button:
function doRequest() {
var req_url, req_type, body;
req_url = document.getElementById('server_url').value;
req_type = document.getElementById('request_type').value;
alert("Connecting to url: " + req_url + " with HTTP method: " + req_type);
req = new XMLHttpRequest();
req.open(req_type, req_url, false, "username", "passwd");// synchronous conn
req.onreadystatechange=function() {
if (req.readyState == 4) {
alert(req.status);
}
}
req.send(null);
}
When I run this on FF, I get a
Access to restricted URI denied" code: "1012
error on Firebug. Stuff I googled suggested that this was a FF-specific problem so I switched to Chrome. Over there, the second alert comes up, but displays 0 as HTTP status code, which I found weird.
Can anyone spot what the problem is? People say this stuff is easier to use with JQuery but learning that on top of JS syntax is a bit too much now.
For security reasons, you cannot use AJAX to request a file from a different domain.
Since your Javascript isn't running on http://api.twitter.com, it cannot request files from http://api.twitter.com.
Instead, you can write server-side code on your domain to send you the file.