POST JSON using JavaScript - javascript

I am trying to do http post using JavaScript but something is going wrong..
I already searched a bit, and found two snippets but none is working.
The first attempt:
<!DOCTYPE html>
<html>
<head>
<script>
function changetext(id) {
var xmlhttp = new XMLHttpRequest();
var url = "http://10.21.6.128:1234/test/test2/teste3/teste4";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var parameters = JSON.stringify({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});
xmlhttp.send(parameters);
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>
In this attempt, there is no JSON being thrown, at my server I get a null input.. I used fiddler to check it, and nothing is being posted..
I searched a few more and found this example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
JSONTest = function() {
var resultDiv = $("#resultDivContainer");
$.ajax({
url: "http://10.21.6.128:1234/teste/teste2/teste3/teste4",
type: "POST",
data: {"Test":"2222","Code":"OP1","Partner":"Test","Prod":"Prod"},
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h1>My jQuery JSON Web Page</h1>
<div id="resultDivContainer"></div>
<button type="button" onclick="JSONTest()">JSON</button>
</body>
</html>
In this case I get a bad request, error 400.
Can someone help me?
Thanks alot in advance ;)

It appears the POST request never gets sent due to Same Origin Policy. Your fiddler screenshot shows an OPTIONS request, which is expected in a cross domain situation. The OPTIONS request is used to find out if the target server supports Cross Origin Resource Sharing (CORS). This is known as a preflight request.
In order for a request to be considered "same domain", the protocol, domain and port all must match.
If you control the target server, you can enable CORS by outputting the response header:
Access-Control-Allow-Origin: *
Note: the * denotes all domains are permitted, you can narrow it to a specific domain if more suitable.
Also, the second code sample in the question will never send JSON, regardless of CORS.
w3.org/cors

Add jQuery to first example and try following,
var parameters = $.param({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});
instead of,
var parameters = JSON.stringify({"Test":"2222","Code":"OP1","Part":"Using","Testing":"Prod"});

Related

How to Connect to a Time Server JavaScript

I am trying to conenct to any external server in order to display server time instead of the machine time in JavaScript.
I have tried reading
How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?
, Understanding XMLHttpRequest over CORS (responseText)
, and How does Access-Control-Allow-Origin header work?
but am very limited in knowledge for this subject, so am confused on how to implement the suggestions to get access to a server time.
I am still getting the error:
Access to XMLHttpRequest at 'https://www.stackoverflow.com/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And don't know how to fix it. This is the current code that I have:
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Server date/time</title>
<script language="javascript" src="main.js"></script>
</head>
<script language="javascript">
document.write("Server time is: " + date);
</script>
<body>
</body>
JavaScript:
var xmlHttp;
function serverTime(){
try {
//FF, Opera, Safari, Chrome
xmlHttp = new XMLHttpRequest();
}
catch (err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (err3) {
// use CPU time.
alert("Using CPU Time");
}
}
}
xmlHttp.open('HEAD',"https://www.stackoverflow.com",false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
return xmlHttp.getResponseHeader("Date");
}
var st = serverTime();
var date = new Date(st);
Ideas on what I am doing wrong and what I can do to get the server time? Thanks!

CORS error for request to api.upcitemdb.com endpoint

I know this is So simple code but somehow its not working. What I what to do is to call GET API of :
https://api.upcitemdb.com/prod/trial/lookup?upc=4011200296908
I want to call this HTML by using JavaScript or Jquery. I have tried many things but its not working. Following code which I have applied but its not working :
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="loadDoc()">Request data</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("responseText" + this.responseText);
} else {
alert("Error");
}
};
xhttp.open("GET", "https://api.upcitemdb.com/prod/trial/lookup?upc=4011200296908", true);
xhttp.send();
}
</script>
</body>
</html>
I also have tried to call same API with Jquery by using Ajax. Following is code for the same :
<!DOCTYPE html>
<html>
<body>
<header>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</header>
<button type="button" onclick="loadDoc()">Request data</button>
<script>
function loadDoc() {
$.ajax({
url:"https://api.upcitemdb.com/prod/trial/lookup?upc=4011200296908",
success:function(response){
alert(response);
},
error: function() {
alert("Error");
}
});
}
</script>
</body>
</html>
That's a classic one!
If you open the developer tab (f12) you may see the following error:
Failed to load
https://api.upcitemdb.com/prod/trial/lookup?upc=4011200296908: The
'Access-Control-Allow-Origin' header has a value
'https://www.upcitemdb.com'
This means that the server https://api.upcitemdb.com don't want you to use his resources on any website but 'https://www.upcitemdb.com'.
If you don't own this site you cannot load it's resources or should ask the admin to give your site the authorization.
If you own it learn more about you CORS configuration.

Pressing the ajax button again after the first time gives a strange error

Basically when I press the button the first time ajax loads perfectly but when I press that same ajax button again it gives me this error
(index):17 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
at sendAJAX (http://etc.../:17:5)
at HTMLButtonElement.onclick (http://etc.../:29:40)
I have found articles about this but they are confusing to a point where I don't know how to integrate those solutions to my script, to get it to work with my script so I need a code example solution based on my exact script not based on some one else's script so I can
better understand this based on my script. I mainly want to know how can I keep calling the same ajax request regardless how many times I press that same button with out errors.
Code example
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/main.css">
<title>AJAX with JavaScript</title>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
function sendAJAX() {
xhr.send();
}
</script>
</head>
<body>
<div class="grid-container centered">
<div class="grid-100">
<div class="contained">
<div class="grid-100">
<div class="heading">
<h1>Bring on the AJAX</h1>
<button id="load" onclick="sendAJAX()">Bring it!</button>
</div>
<ul id="ajax">
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
sidebar.html
<section>
<h2>Welcome to the wonderful world of AJAX</h2>
<p>This content provided to you dynamically by the XMLHTTP Request Object</p>
</section>
You create your xhr element only once, so if sendAJAX is called a second time, then send is called on an XMLHttpRequest that was already send.
After send is called the state of the xhr obeject is not opened anymore and because of that you get the error message.
You can solve the problem by creating new XMLHttpRequest for each sendAJAX call.
function sendAJAX() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
xhr.send();
}
Or by only moving open into the sendAJAX:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
function sendAJAX() {
xhr.open('GET', 'sidebar.html');
xhr.send();
}
XMLHttpRequest.open()
Note: Calling open for an already active request (one for which open() has already been called) is the equivalent of calling abort().

Can't Access to API using jQuery

I am using pCloud Api to get download link form the request. It is a GET request. When I request form browser I can get a response. But when I use jQuery I get a response code result : 7010
Api Request URL : https://api.pcloud.com/getpublinkdownload?code=8eM7
I get this response when requesting from browser:
{
"result": 0,
"expires": "Mon, 07 Aug 2017 00:12:50 +0000",
"dwltag": "aftsTab2SLkC4MDXRdp6Am",
"path": "\/cBZkvG2cXZNPjykVZZZChTDE7ZNVZZj5JZkZSqfRZIXZqkZmVZR7Zd7Z4ZfkZIZyVZokZbXZ3VZFkZ77ZIgCcZ14l5zXbx6p4GwdeEPdF1707nIPm7\/image%20%286%29.jpg",
"hosts": [
"p-def2.pcloud.com",
"c166.pcloud.com"
]
}
I need this hosts and path to generate the download link. I just need this -https://c166.pcloud.com/cBZkvG2cXZNPjykVZZZChTDE7ZNVZZj5JZkZSqfRZIXZqkZmVZR7Zd7Z4ZfkZIZyVZokZbXZ3VZFkZ77ZIgCcZ14l5zXbx6p4GwdeEPdF1707nIPm7/image%20%286%29.jpg
I have to use jQuery/JavaScript to get this response. I tried PHP file_get_contents(); it works but this link will work only form the ip address you request for. So, I must use JQ/JS.
My Code:
$(document).ready(function(){
function httpGet(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
console.log(httpGet("https://api.pcloud.com/getpublinkdownload?code=8eM7"));
});
Thanks for trying to help me.
It seems pCloud server is checking referrer.
In most case, servers will refuse the accesss not coming from itself.
Only web browsers arriving from a small set of approved (login) pages are given access; this facilitates the sharing of materials among a group of cooperating paysites from https://en.wikipedia.org/wiki/HTTP_referer
In following html, script ran and got image url successfully, but browser raised error when it was trying to load image.
<html>
<head>
</head>
<script
src="http://code.jquery.com/jquery-3.2.1.js"
integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<body>
<h1>Load Image from pCloud </h1>
<img class="loading">
<script>
$(document).ready(function() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText){
var host = JSON.parse(this.responseText).hosts[0];
var path = JSON.parse(this.responseText).path;
}
$(".loading").attr("src", "https://" + host + path);
}
};
xhttp.open("GET", "https://api.pcloud.com/getpublinkdownload?code=8eM7", true);
xhttp.send();
});
</script>
</body>
</html>

Ajax Pull Content From another webpage

So I got this code for pulling rss feeds from another website (i asked them, and they gave me permission) I Don't know what should i Write in TAG1 and TAG2. Basically that is just my problem:
Here is the html (its an ajaxed page)
<!doctype html>
<html lang="hu">
<head>
<title>Videók</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="../js/videok.js"></script>
</head>
<body>
<h2>Van egy jó videód? Töltsd fel és kikerülhet az oldalra!</h2>
<div id="videok"></div>
</body>
</html>
And here is the Javascript for pulling
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "choose url";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
You won't be able to use javascript to pull from another web page because javascript is sandboxed when in browsers. Sandboxing means that you will only be able to send requests to the same domain that the javascript originally came from (also known as the 'same orgin policy').
You can use a serverside language like php to do the pulling and then hand it down to the javascript through ajax.
The code that you posted looks like it just makes a simple ajax call but it shouldn't work when trying to request an RSS from anything other than your own site.
It's better that you have the server side of your application fetch data for the xml and format the data how you want it.
You would have the Ajax request hit your server's end point, then your server will fetch the xml data, format it properly and respond to the request with the correct formatted data.

Categories

Resources