Jquery ajax function returns wrong webpage - javascript

I have 2 local servers connected to a local switch. Ip adresses: 192.168.0.10 and 192.168.0.20. I am trying to get some data from the second one to the first using jquery Ajax as follows:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: "GET",
url: "192.168.0.20/d",
dataType: '',
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
window.alert(response);
}
});
});
});
</script>
</head>
<body>
<button id="get-button">Toggle</button>
</body>
</html>
When I put "192.168.0.20/d" in the browser url I get "data = xyz" as expected but using the method above I get that exact script back, its returning itself(192.168.0.10) instead of 192.168.0.20. How can I resolve this?
Thanks.
Edit.
The following gets rid of the Access-Control-Allow-Origin error but the returned data does not appear in the message box but it is present in developer mode.
$.ajax({
type: "GET",
crossDomain: true,
dataType: "JSONP",
url: "//192.168.0.20/d",
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
window.alert(response);
}

You need to alter your URL to:
url: "//192.168.0.20/d"
The way you've specified it now is as a relative URL. In other words it will assume that you want to make the request to the current domain, and that 192.168.0.20 is a subfolder of your website. You'd have the same problem if you created a hyperlink to it - it's not an ajax issue, it's the way browsers interpret URL fragments. This normally helps programmers when deploying the same site to multiple environments (e.g. dev, test, live) on different servers, so they don't have to replace all the URLs to point to a different place just because the deployed location changed. However in this case you're pointing to a resource on another server entirely, so that situation doesn't apply.
If you place the // before it, this indicates that it's an absolute URL (so always points to exactly the same place, no matter where the originating page is deployed) and that the first part following the slashes is a domain name or IP address.
(N.B. The // without http: or https: before it means that the browser will use the same protocol as the originating page is currently running under. So if your page is loaded via HTTP it'll make the ajax request via HTTP too, and if your page is loaded via HTTPS it'll make the ajax request via HTTPS. If that's not suitable for this scenario then you can add http: or https: at the beginning as appropriate.)
Look at https://jsfiddle.net/9uyuj96f/ (your code) and https://jsfiddle.net/9uyuj96f/1/ (fixed version) and watch the ajax request in the browser's network tools to see the difference.

Related

Ajax Request to AWS API Gateway can not parse json response

I am testing the code here:
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_get
Here is the code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var processJSON = function(data, textStatus, xhr) {
alert(xhr.status);
}
// for whatever reason, the following URL is not working any more, so you won't be able to test it anymore.
var myURL='https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223';
// var myURL="https://jsonplaceholder.typicode.com/users"
$("button").click(function(){
$.ajax({
url: myURL,
dataType: "json",
contentType: 'application/json',
success: processJSON
});
});
});
</script>
</head>
<body>
<button>Send Request</button>
</body>
</html>
As indicated in the code, I am trying to parse the response from this URL:
https://ckeqt3eoea.execute-api.us-east-1.amazonaws.com/pettest/test?name=223
And you can go to that URL directly and find out that the response from the AWS-API-Gateway is simply:
{
"cc":"dd",
"name":"ee"
}
I was able to use the above javascript to parse other json responses from other sources. But I am pulling my hair trying to parse the above response from AWS-API-Gateway.
if you uncomment the second line of var myURL, you will see that the code just really works for other URLs.
==========
In response to existing answers:
I tried both json and jsonp. Both worked for other URLs (including the one I commented). But neither works for the AWS Gateway API.
I also updated the code to use a named function. But again, it works for other URLs, but not for the AWS URL.
I tested it on Firefox and Safari.
It's the data type. You are telling jQuery to expect jsonp callback. What you are looking for is dataType: "json".
UPDATE
I just tested your code. Issue is that you don't have an OPTIONS method defined in your pettest/test resource. Using the API Gateway console, open the test resource (assume pettest is the stage and test is the resource), then use the "Actions" dropdown button to Enable CORS. This will automatically create the OPTIONS method and setup the required headers in your GET method.
Worked for me with your API. Probably doesn't matter, but instead of using 'resp' as the variable label, I used 'data'.
Also, calling a named function rather than embedding the function inline
function processJSON(data) {
alert(data.name);
}
dataType: "json",
contentType: 'application/json',

How to create an ajax request within google scripts with '$' variable error?

I'd like to use the ajax() method to perform an AJAX Request. I've tried to create the below functions within scripts.google.com, but I get the following error:
function AjaxCall() {
var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'https://worker-aws-us-east-1.iron.io/2/projects/',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});
}
Error:
ReferenceError: "$" is not defined. (line 5, file "Code")
Is there a way to get around this issue?
It appears that jquery isn't sourced in your HTML. Keep in mind that jquery is a client side, javascript library -- so the browser needs to load the jquery javascript file. In other words, a valid reference needs to be in the HTML that is returned to the client browser.
Your comment indicated that you tried:
<script src="code.jquery.com/jquery-2.1.1.min.js"></script>
Try updating that to:
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
If you don't include the "http://" (or "https://" or "//") in the front of the URL, the browser thinks it's a relative path and will try to load that from the current directory (and that probably isn't what you were trying to do). So, if the page that you were viewing was
http://www.examplesite.com/example.html
Then, the script tag you showed in your comment would try to load jquery from
http://www.examplesite.com/code.jquery.com/jquery-2.1.1.min.js
This is likely returning a 404 error -- check your javascript console to see if it's receiving an error when trying to load the jquery script.
Also, in most cases, it's recommended that you put the script tag at the bottom (right before the closing body tag). This keeps the page rendering from being blocked as the browser download the js file. This is not likely causing the problems you were originally seeing -- just thought I'd mention it since your comment potentially indicated that you were loading it right before the ajax call.

jQuery cross domain ajax call - Interpreted as script but transferred with MIME type text/xml

Trying to make a REST web service call using an ajax call. Whenever I try to run it, I receive the error, Interpreted as script but transferred with MIME type text/xml. Here's my code ("website" is actual website where web service is):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function testCall() {
var webMethod = "website";
var un = 'un'
var pw = 'pw'
var parameters = "username=un&password=pw&change_ticket_number=CRQ000000011334&restuser=TEMPESP&restpass=restpw";
$.ajax({
url: webMethod,
type: 'Post',
data: parameters,
crossDomain: true,
username: un,
password: pw,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType: 'jsonp',
success: function(data) {
alert('Success: ' + data);
},
error: function(errorThrown){
alert('Try again ' + errorThrown);
}
});
}
I have been searching all over the web and this website for something like this but I haven't had any success.
I have initially had my dataType as "xml" as that's what the web services provdies but changed it to "jsonp" when I read about cross domain calls.
The parameters are what the web service is looking for. If I was to open an internet browser and put the url + parameters, it does show me the xml message.
I'm not sure how much control I have over the web service itself so my hope would be to figure out a way on how to translate this back to xml after jsonp successfully brings it over.
So the question remains, am I able to change my code in order to make this work, leaving the web service as is? If it's truly not possible, what needs to be done to the web service? Keeping in mind xml is being used.
Thank you for any help you can provide.
The JSONP data format is a JavaScript program consisting of a function call (to a function defined in the URL) with the requested data as the argument.
You are getting the error because you are making a JSONP request and getting XML.
Change the server so it returns JSONP or change the JavaScript so it expects XML (and also change the server so it gives your site permission to read the XML using CORS).

jquery ajax - calling my asp.net web api gives a wrong url and a 404 not found message

I'm writing a small ASP.NET MVC site which also includes a WEB API in it that I wrote.
I've configured the project on my local IIS as http://localhost/mysite
On the main page of my site I'm including a js script that I wrote:
<script src="#Url.Content("~/Content/js/home.js")"></script>
on the page ready event of that js I call:
$.ajax({
url: 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
when looking with Fidler I see that the page call returns a 404 since it doesn't try to load it to the relative path I'm in (http://localhost/mysite) and it tries to load the root of the server - so the call looks like this http://localhost:80/api/getdetails
when I was writing web forms I used to do ajax calls such as this all the time and it always worked.
what am I missing?
Thanks
What I ended up doing is in my layout html I've added a js var:
var baseUrl = '#Url.Content("~/")';
then on my ajax call I've added that base url:
$.ajax({
url: baseUrl + 'api/getdetails',
accepts: 'application/json',
cache: false,
type: 'GET',
success: function (data) {
alert(data);
}
});
this does the trick no matter how the page looks like. even if I navigate to http://localhost/mysite/home/index
It's probably not the perfect solution, and I definitely think the old webforms way which worked was better - but I guess there are pros and cons to any technology.
Still would be happy to hear if someone has a better solution. for now - this does the trick.
When you navigate to
http://localhost/mysite
The behavior is a little different from
http://localhost/mysite/
Try that to confirm. Without the trailing slash, the "mysite" looks like a document name, not a folder, so relative paths would form from the root of the server.
What you may need to do is pass in the site content URL into your home.js and form absolute paths from it in your code.

jQuery cross domain post redirect

I'm trying to use jQuery to POST a form to chargify. My "Net" tab shows a 302 redirect (in red indicating an error), but jQuery is throwing a 404 error. Is it possible to preform a x-domain, post, redirect request from the browser or will I need to use proxy?
$(function() {
var endpoint = "https://api.chargify.com/api/v2/signups"
$('#new_sub_form').on('submit', function(e){
e.preventDefault()
var jqxhr = $.ajax({
type: "POST",
url: endpoint,
crossDomain:true,
data: $('#new_sub_form').serialize(),
success: function(data, textStatus, request){
console.log(request.getResponseHeader('Location'));
},
error: function (request, textStatus, errorThrown) {
console.log(request.getResponseHeader('Location')); // Returns null
}
})
})//on('submit')
})//ready()
UPDATE (more info):
So I realized the 302 was redirecting me to a page that didn't exist on my server. Unfortunately once i fixed this, I still have an issue. From what I can tell, i POST to chargify, they then send a 302 back to the browser with the URI I specified. This URI is located on my server (localhost for now). Once the user is redirected my server parses the response and returns JSON. I tested the Response Header location via copy and paste into another tab and works fine.
Chargify is only offering https, while my localhost is http. Would this cause the error?!
HTTP Response
Ran into to a very similar problem the other day. However im using ASP.NET MVC4.
Its not enough if you use crossDomain:true u also need to add,
dataType: 'json or html depending on the return value',
xhrFields: {
withCredentials: true
},
You will also need to add these headers "Access-Control-Allow-Origin:"http://yourdomain.net" ,
Access-Control-Allow-Credentials:true" and maybe "Access-Control-Allow-Methods:GET,POST" in your case aswell to your RESPONSE.
Chargify Direct does not support ajax/CORS.
You should use a "transarent redirect", as they describe, which is basically a standard form post redirecting the user to Chargify, and they will redirect the user back again to the URL you specify in the payload. This means the user will briefly leave your site and return back to it.
<form method="post" action="https://api.chargify.com/api/v2/signups">
</form>
Docs: https://docs.chargify.com/chargify-direct-introduction

Categories