Request Web Service to get JSON - javascript

I need to hit web service URL which is giving me JSON object and use basic authentication. How can I perform the the same in JavaScript. I am using the code below, but nothing happens on browser.
<html>
<head>
<title>Hello World</title>
<script>
function send_with_ajax()
var httpRequest = new XMLHttpRequest();
httpRequest.open("GET", 'url of service', true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
httpRequest.send();
httpRequest.onload= function() {
if (httpRequest.readyState == 4)
{
var _tempRecommendations = httpRequest.responseXML;
window.alert(httpRequest.response);
window.alert(httpRequest.responseText);
window.alert(_tempRecommendations);
}
};
};
</script>
</head>
<body onload="send_with_ajax()"></body>
</html>

check jQuery out for this action. It would result in something like
$.get("http://yourRestprovider.com/yourResource",function(data){
//handle your data
},"json");
please specify what you mean with basic authentication since I see no approach of authenticating against the server in your code snippet!

(You don't need JQuery for this.)
First make sure the inner function is running at all, so try setting the function to onreadystatechange instead of onload.
As for authentication: If your domain (the thing that replaces 'url of service') has the same origin as the page the script is in, and you're already doing some sort of authentication which stores a login session cookie, you don't need to do anything else.

Hi i am using below code : after that it just shows loading on browser.
<html><head>
<title>Hello World</title>
<script src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a1/jquery.mobile-1.0a1.min.js">
</script>
<script type="text/javascript">
function send_with_ajax()
{
$.ajax
({
type: "GET",
url: "https://url with params",
dataType: 'json',
async: false,
username: 'abc',
password: 'def',
data: '{ "comment" }',
success: function (){
alert('Success!');
}
});
}
</script>
</head>
<body onload="send_with_ajax()"></body>
</html>

Related

How do I add basic auth headers to a post request that returns html?

For one of the projects I am working on, there is a POST endpoint protected by basic auth that returns a HTML form. This is hosted using a express server and protected using passport's basic auth. I want to have another HTML form that has a button that, when clicked, loads that html in the browser. I tried to have a form similar to this one:
<form method="post" action="http://username:password#localhost:8080/endpoint">
<input type="submit">
</form>
But when the button is clicked and I check the auth headers on the server, they seem to be unset (req.headers.authorization = undefined). I know that I can set the auth headers using Javascript, but if I do that, I'm not sure how to load up the html in the browser on that page. So, how do I deal with an endpoint that requires basic auth headers, is accessed using post and returns HTML? This seems like it should be easy to do, but I'm not sure how to do it.
You need to add the auth headers in javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
<input type="submit">
</form>
<script type="application/javascript">
$("#myForm").submit(function (e) {
var url = 'http://localhost:8080/endpoint';
var username = 'username';
var password = 'password';
$.ajax
({
type: "POST",
url: url,
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
data: '{ "comment" }',
success: function (response){
$(body).empty();
$(body).html(response);
}
});
e.preventDefault();
});
</script>
</body>
</html>

Azure Face API identify - Bad request 400

I am trying below snippet of code for face identify of azure samples with proper Subscription-Key. I get bad request 400 - can any one please help me how to send request body to work for this ajax call.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://api.cognitive.azure.cn/face/v1.0/identify?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","MY_ACCESS_KEY");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
The url seems to be bad here. Two things: 1) You need to append location before api.cognitive.microsoft.com and 2). .cn should be .com. Your url may look like this, depending on your location:
url: "https://westus.api.cognitive.azure.com/face/v1.0/identify?"
More locations and details are here: https://eastasia.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395239
Try
data: JSON.stringify({name: "Test"})

Getting Undefined when reading back a POST from AJAX

If this is a re-post of an already existing. I looked a bunch of different issue already posted about this but didn't feel any matched my issue. If there is one please link it.
I'm trying to learn AJAX and have a form that takes two inputs a serverName, and a isLive. As well as a button to add a server to the list. I already made a json file that has two servers in it and when I GET info from it to update the list it lists the server's serverName and isLive fine. When I go to POST information all I get back when the list is updated is undefined.
Using console logs I know that the information is being passed from the form to Object to be sent by AJAX and that it seems to trigger the success function, but when I look there is nothing added to the Json and it says the fields are undefined.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<h1>Server List</h1>
<ul id="servers">
</ul>
<h4>Add a Server</h4>
<p>Server Name: <input type="text" id="serverName"></p>
<p>Offline or Online: <input type="text" id="isLive"></p>
<button id="add-server">Add!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
$(function() {
var $servers = $('#servers');
var $serverName = $('#serverName');
var $isLive = $('#isLive');
$.ajax({
type : 'GET',
url: 'servers.json',
success: function(servers) {
$.each(servers, function(i, server) {
$servers.append('<li>Server: '+ server.serverName +', Status: '+server.isLive+'<li>');
});
},
error: function() {
alert('Error loading server status!');
}
});
$('#add-server').on('click', function() {
var server = {
serverName: $serverName.val(),
isLive: $isLive.val(),
};
console.log(server);
$.ajax({
type: 'POST',
url: 'servers.json',
data: server,
success: function(newServer) {
$servers.append('<li>Server: '+ newServer.serverName +', Status: '+newServer.isLive+'<li>');
},
error: function(){
alert('error saving server');
}
});
});
});
servers.json
[{"serverName":"vanilla","isLive":"offline"}, {"serverName":"SkyFactory","isLive":"Online"}]
You can't modify a file in the server with JavaScript. Check this may help:
Use JQuery to Modify external JS File

load json data into js

I am learning how to load json data into .js file. I have created a employee.json file. I saved my js and json file and on the desktop. What I trying to do is to put all the id in json files into an array in the js. I do not know what could be wrong. Hope someone could help me out. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON with jQuery</title>
</head>
<body>
<p id="demo"></p>
<h1><h2>
<script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
}
});
document.getElementById("demo").innerHTML = res.toString();
</script>
</body>
</html>
{
"person": [
{
"id" : 1,
"firstName" : "Lokesh"
},
{
"id" : 2,
"firstName" : "bryant"
}
{
"id" : 3,
"firstName" : "kobe"
}
]
}
Error 1: Typing error. <script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>. You mistyped the src of the script, accidentally adding another another <script> start tag.
Error 2: Misplaced statement. document.getElementById("demo").innerHTML = res.toString(); should be placed in the success callback function, so it will be executed only after the server responds. If it executes prematurely, res will still be [].
Error 3: type: 'GET' should be method: 'GET', according to the docs (though 'GET' is default so you don't need to explicitly write this).
Use this:
<p id="demo"></p>
<h1><h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
You can't use the local json to read. it gives cross origin request failure. so deploy both the files (html and json) into a we server and execute. or place the json data onto some web url(http://somesite/myjson) and then request that url and see.
First of all, the JSON shouldn't be existed as in physical "file". It has to be generated by a backend language / web service etc. The JSON tags inside a manually created "file" have high chance of data invalidity upon parsing.
Solution
Use a Web Service to generate valid JSON output. And from Javascript end, use:
JSON.stringify( data );

$.ajax not working properly on IE6

Basically, I have something like this:
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
dataType: 'json'
});
This code is working in all tested browsers (IE7/8, chrome, safari, firefox) but in IE6 the success function is not called.
I used Fiddler to see what's going on in the HTTP requests, and everything seems normal, I get the expected result as an HTTP answer but success doesn't seem to be called in IE6, same for onerror.
Any thoughts?
Try using complete instead of success. If it fires consistently then you can evaluate the status code to determine if it was successful...
$.ajax({
type: "GET",
cache: true,
complete: function(xhr) {
if(xhr.status != 200) {
throw "Error!";
return;
}
var data = xhr.responseText;
}
});
Are you sure it's not just a cache thing? Remove your browsers cache and test again.
A good test case would be getting rid of the 'cache' option, and also making it a POST request (since GET ajax calls are always cached in ie6).
You don't mention the server-side code you're using. I had some issues with jQuery AJAX calls in IE when using ASP.NET on the server side (a ashx handler). They went away when I read the request fully before starting to write the response (even though in my case I was using POST, not GET request, so the body of the request contained some data).
I wrote the following simple ASP.NET project to test your issue in IE6. However I'm unable to reproduce (IE6 SP2 running in virtual machine hitting IIS 7.5 shows the alert box from success handler properly). Could you try running it in your environment and reporting whether it works from IE6 for you?
Note: Sometimes when I cleared IE6 cache and commented out the "SetCacheability" line in ashx.cs, the first click on "Send" button would not show the success alert box, although subsequent clicks did show it. Maybe all you need is adding "no-cache" headers to the call response in your implementation?
file index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX GET test</title>
</head>
<body>
<input type="button" id="test" value="Send" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$("#test").click(function () {
$.ajax({
url: "Api.ashx?param=one",
cache: true,
type: "GET",
dataType: "json",
success: function (data) {
alert("Success, result = " + data.result);
},
error: function (request, status, err) {
alert("Error");
}
});
});
</script>
</body>
</html>
file Api.ashx
<%# WebHandler Language="C#" CodeBehind="Api.ashx.cs" Class="AjaxTest.Api" %>
file Api.ashx.cs
using System.Diagnostics;
using System.Text;
using System.Web;
namespace AjaxTest
{
public class Api : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
var param = context.Request["param"]; // this flushes the request
Trace.WriteLine("Request: \"" + context.Request.RawUrl + "\", param: \"" + param + "\"", "** Debug");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Write("{\"result\":\"" + param + "\"}");
}
}
}
What happens if you add a failure function, and alert out the responseText within there?
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
error: function(data) {
alert(data.responseText);
},
dataType: 'json'});
http://docs.jquery.com/Ajax/jQuery.ajax#options

Categories