I'm trying to make a very simple program that sends a variable to a server, to write out then.
According to Opera, it gets an HTTP 400 (Bad Request) at the end of Display().
.jade file
button(type='button', onclick='Display()') Display data
#modify
p Lorem ipsum Display
script
include main.js
main.js
function Display(){
var xhttp = new XMLHttpRequest();
var parameter = { "Name": "Katamori" };
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("modify").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "displayer.js", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(parameter);
};
displayer.js
function (req, res) {
if (req.method == 'POST') {
var jsonString = '';
req.on('data', function (data) {
jsonString += data;
});
req.on('end', function () {
console.log(JSON.parse(jsonString));
});
req.on('error', function () {
console.log("ERROR!");
});
}
}
I attempted to change parameter from JSON to simple text (with RequestHeader too), and in that case, I got an HTTP 404 error.
What's the reason and what's the proper solution?
You aren't sending JSON, serialize your data to JSON and send it
xhttp.send(JSON.stringify(parameter));
Or you can even send it in another way, like below:
function display(){
var http = new XMLHttpRequest();
var params = "name=Katamori";
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
document.getElementById("modify").innerHTML = http.responseText;
}
};
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.open("POST", "/", true);
http.send(params);
}
server-side code
app.post("/", function(req, res){
var jsonString = '';
req.on('data', function (data) {
jsonString += data;
});
req.on('end', function () {
console.log(jsonString); // name=Katamori
});
});
w3schools
It works for me.
Thanks, i hope it will help you
Related
So, I have a JS script that sends a request to the server and that works fine. However, I want the frontend to recieve a response containing some information and read it on the frontend and execute a function.
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
if (request.response.result == "Success") {
console.log("Result is success")
window.location = request.response.url;
}
}
My controller looks like this.
[HttpPost("/page/upload")]
public IActionResult Upload()
{
*working parts pertaining to reading the request are omitted*
var redirectUrl = Request.Host + "/" + page.PageURL;
return Json(new { result = "Success", url = redirectUrl});
}
What I want is for my JS script to access the returned Json and its contents. How would I do this?
Try using the following code. It will subscribe the readystatechange event and run when API response has been received
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
request.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var responseData = JSON.parse(this.responseText);
if (responseData.result == "Success") {
console.log("Result is success")
window.location = responseData.url;
}
}
});
});
I know I could just do this with a global, but I'd like to be object oriented if I can. If my request response returns a false for that 'ok' value, I'd like to log the data that was originally posted. Is that data accessible by a listener function on the request object?
Thanks!
function reqListener () {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
//Here I want to log the data that I originally posted
console.log(__TheFormDataThatWasPassedtoSend__);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load",reqListener);
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
So the problem you have is needing to use data known when you create the eventListener when the eventListener actually fires. Below is your code to do this with formData
function reqListener (formData) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
if (jsonResponse['ok'] == false) {
console.log(formData);
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() { reqListener.call(this,formData) });
xhr.open('POST',urltopostto, true);
// Set up a handler for when the request finishes.
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
console.log('Uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
I have a one variable file like this.
var geography = [
{ id:"Country", header:"", width:150},
{ id:"Capital", header:"Capital", width:150},
{ id:"Falg", header:"Falg", width:150},
{ id:"Language", header:"Language", width:150},
{id:"Population", header:"Population", width:150},
],
Now I wanted to load this data from the json. I placed this data into JSON file and Using this code.
getGeography function(){
var geography;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data.json",true);
}
Now from here how to store into a variable and return that.
It should be read when the ready state of xmlhttp is 4 and response status is 200. You should parse the response with JSON.parse(). However you can't return the value from the function. Because XMLHTTPRequest is asynchronous by default.
function getGeography() {
var geography;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data.json",true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
geography = JSON.parse(xmlhttp.responseText;)
}
}
}
Instead of returning geography you have to programmatically read the value of geography when the AJAX request is complete. Something like this (read this):
Instead of writing code like this:
function anotherFunc() {
var geography = getGeography();
thenDoSomething(geography);
}
Write like this:
function anotherFunc() {
getGeography();
}
function getGeography() {
var geography;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data.json",true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
geography = JSON.parse(xmlhttp.responseText);
thenDoSomething(geography);
}
}
}
It's like handing over the control of execution of rest of the code to getGeography() function, instead of expecting a return value from the function and then using that value. The getGeography() function resumes execution of rest of the code with the value received from AJAX response, when the AJAX call completes.
I'm not a fan of jQuery but in this case, you would probably benefit from this.
$.get( "ajax/test.html", function( data ) {
// data is your result
console.log(data);
console.log(JSON.parse(data));
});
https://api.jquery.com/jquery.get/
Here is how to use XMLHttRequest() :
<script>
const req = new XMLHttpRequest();
var geography = [];
req.onreadystatechange = function(event) {
// XMLHttpRequest.DONE === 4
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
geography = JSON.parse(this.responseText);
console.log(geography);
alert("Great Success : check console !");
} else {
alert("Something has gone really Bad !");
}
}
};
req.open('GET', 'data.json', true);
req.send(null);
Be careful to use correct JSON :
[
{"id":"Country","header":"","width":150},
{ "id":"Capital","header":"Capital", "width":150},
{ "id":"Falg","header":"Falg","width":150},
{ "id":"Language","header":"Language", "width":150},
{ "id":"Population", "header":"Population", "width":150}
]
Firstly, I want to confirm that this question is not duplicated with other similar questions on stackoverflow, because my question is only based on javascript, NO jquery.
I wrote website https://www.emojionline.org. Because this site is small, I don't want to use JQuery. I tried to test with Jquery to solve this problem is ok, but I only want javascript without jquery.
My question is problem that return value from ajax callback function. I wrote as follows:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'emoji.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function returnJSON(){
var jn = '';
loadJSON(function(response){
jn = JSON.parse(response);
});
return jn;
}
var json = returnJSON();
However, the json is null when I use console.log to write? What is this problem? Please help me solve it!
Synchronous request example:
function loadJSON(url) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open('GET', url, false);
request.send();
if (request.readyState === 4 && request.status === 200)
return request.responseText;
}
// An example using ipify api (An IP Address API)
var json = loadJSON('https://api.ipify.org?format=json');
console.log(json);
Or asynchronous request example, using the Promise API and error event handler:
function loadJSON(url) {
return new Promise(function (resolve, reject) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open('GET', url, true);
request.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
resolve({status: this.status, body: JSON.parse(this.responseText)});
} else {
reject({status: this.status, body: this.responseText});
}
}
};
request.send();
});
}
// An example using ipify api (An IP Address API)
loadJSON('https://api.ipify.org?format=json')
.then(function (response) {
console.log(response);
})
.catch(function (errorResponse) {
console.log(errorResponse);
});
xobj.open(method, url, async, user, password);
xobj.send(null);
reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/open
I'm new to javascript which should be really simple to solve, but I am lost as of now.
I have a url: http:getall.json
Using JavaScript (not JQuery or php. Just JavaScript), I want to read this JSON string and parse it. That's it.
access to your url doesn't work, you should show the JSON result. In javascript to get JSON object with AJAX request you can do something like this:
request = new XMLHttpRequest;
request.open('GET', 'http://v-apps-campaign.com/dunkindonuts/main/get_allStore', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
your result will be in the data variable.
JSONP calls:
function getJSONP(url, callback) {
var script = document.createElement('script');
var callbackName = "jsonpcallback_" + new Date().getTime();
window[callbackName] = function (json) {
callback(json);
};
script.src = url + (url.indexOf("?") > -1 ? "&" : "?") + 'callback=' + callbackName;
document.getElementsByTagName('head')[0].appendChild(script);
}
getJSONP("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function(jsonObject){
//jsonObject is what you want
});
Regular ajax ajax call:
function getXHR() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
try {
return new ActiveXObject('MSXML2.XMLHTTP.6.0');
} catch (e) {
try {
// The fallback.
return new ActiveXObject('MSXML2.XMLHTTP.3.0');
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
function getJSON(url, callback) {
req = getXHR();
req.open("GET", url);
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObject = null,
status;
try {
jsonObject = JSON.parse(req.responseText);
status = "success";
} catch (e) {
status = "Invalid JSON string[" + e + "]";
}
callback(jsonObject, status, this);
}
};
req.onerror = function () {
callback(null, "error", null);
};
req.send(null);
}
getJSON("http://v-apps-campaign.com/dunkindonuts/main/get_allStore", function (jsonObject, status, xhr) {
//jsonObject is what you want
});
I tested these with your url and it seems like you should get the data with a jsonp call, because with regular ajax call it returns:
No 'Access-Control-Allow-Origin' header is present on the requested resource
with jsonp it gets the data but the data is not a valid json, it seems your server side has some php errors:
A PHP Error was encountered
...
In your HTML include your json file and a js code as modules
<script src="/locales/tshared.js" type="module" ></script>
<script src="/scripts/shared.js" type="module" ></script>
file content of tshared
export const loc = '{"en": { "key1": "Welcome" },"pt": {"key1": "Benvindo"} }'
file content of shared
import {loc} from "./../../locales/tshared.js";
var locale = null;
locale = JSON.parse(loc) ;
Adapt path and names as needed, use locale at will.