I have some problem with transfer of variable outside the function.
It's seems to be very simple but I have some problem with it.
var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);
function XHRhandler() {
if (xhr.readyState == 4) {
var json;
if (JSON && JSON.parse) {
json = JSON.parse(xhr.responseText);
} else {
eval("var json = " + xhr.responseText);
}
console.log(json);
myJson= json;
xhr = null;
}
}
console.log(myJson);
What I need is to pass the data from local variable json to global myJson;
But when i do console.log(myJson) i get undefined.
What is the problem?
Thank you
Try moving the statement console.log(myJson); inside your if condition or alternately initialize your variable with some value. It seems your statement is getting called before it is getting populated with any value.
The XMLHttpRequest is async so it is not done yet when you try to write the myJson variable to console. Wrap it in a function and call that function after the XMLHttpRequest is completed instead.
var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);
function XHRhandler() {
if (xhr.readyState == 4) {
var json;
if (JSON && JSON.parse) {
json = JSON.parse(xhr.responseText);
} else {
eval("var json = " + xhr.responseText);
}
console.log(json);
myJson= json;
xhr = null;
writeToConsole();
}
}
function writeToConsole() {
console.log(myJson);
}
Related
In a view of my project i'm doing an xhr request to a yii2 controller
The request is structured like this in my view
var xhr = new XMLHttpRequest();
xhr.open('POST', '$urlToController', true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
};
// Print on console first
console.log({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken});
xhr.send({ id: JSON.stringify($('#grid').yiiGridView('getSelectedRows')), _csrf : csrfToken}});
and this is my controller:
public function actionTargetController() {
if(Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
if (Yii::$app->request->isPost) {
$post = Yii::$app->request->post();
return $post; // Print $post
}
}
}
When i try to send the data with xhr.send() i don't receive nothing in the yii2 controller and the response i get is always '[]' (empty array)
I've also tried to send data with the FormData Object but the result is the same.
Where am i doing wrong? Thanks in advance for all the help
PS:
_csrf param isn't pass either so i've disabled csrf validation in the beforeAction method.
Change the mime type and change the data that you post.
var xhr = new XMLHttpRequest();
xhr.open('POST', '$urlToController', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // <------ other mime type
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
}
};
var params = $('#grid').yiiGridView('getSelectedRows')
.map(function (value) { return "selectedRowIds[]=" + value; }).join("&");
xhr.send("_csrf=" + csrfToken + (params ? "&" + params : ""));
Now you could get the posted data in the action with:
$post = Yii::$app->request->post('selectedRowIds');
You get an array of integers.
You could use jQuery for this too, since you're using it already. Much easier:
var params = {selectedRowIds: $('#grid').yiiGridView('getSelectedRows'), _csrf : csrfToken};
$.post('$urlToController', params).done(function(data) {
console.log(data);
})
I'm attempting to send and receive data from an input to PHP through an XHR request. I have successfully managed to create a connection to PHP without passing data as a parameter within the send method.
However, if I attempt it, I receive the error.
Here is the JavaScript (updated!):
function serialize(obj, prefix) {
var str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
function xhrRequest(data, method, url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
callback(xhr.responseText);
} else {
callback(null);
console.log("XHR Request Failed");
}
}
}
xhr.open(method, url, true);
xhr.send(JSON.stringify(data));
}
// Calling xhrRequest
xhrRequest({ valueA: input.value }, "POST", "post.php", function(data){
alert(data);
});
PHP is just an echo of the value to make sure it was passed (updated!):
if(isset($_POST["value"])){
echo $_POST["value"];
} else {
echo "no value set";
}
I am aware that you can pass parameters like this "valueA=" + input.value within the send method, but it seems really unnecessary (especially if there are multiple values).
So, how would I get this to work? What are some improvements / changes I might be able? to make.
Apologies if it seems very obvious, but I learnt jQuery before vanilla JavaScript, unfortunately. So I am trying to learn the vanilla way, and am used to how jQuery works.
Thanks! :)
EDIT:
Using #adeneo's technique does in fact semi-work! However, using the updated PHP, I alwasy receive "No value set". Why is the value not passing, even when I use "valueA=" + input.value?
The problem is that onreadystatechange fires multiple times during a request, you can't just use an if/else clause as it will fire four times before the status is 4 (states 0-3).
It should look like
function xhrRequest(data, method, url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(xhr.responseText);
} else {
callback("XHR Request Failed"); // the error
}
}
}
xhr.open(method, url, true);
xhr.send(JSON.stringify(data));
}
// Calling xhrRequest
xhrRequest({ valueA: input.value }, "POST", "post.php", function(data){
alert(data);
});
To properly serialize the object to www-urlencoded data, you could use this one, borrowed from here
function serialize(obj, prefix) {
var str = [],
p;
for (p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
var data = serialize({ valueA: input.value });
xhrRequest(data, "POST", "post.php" ...
etc, or even add it to the xhrRequest function for convenience.
Here is a script I wrote a long time ago:
var objXMLHttp;
try{
objXMLHttp = new XMLHttpRequest();
} catch(e){
var xmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0'
,'MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0'
,'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP'
,'Microsoft.XMLHTTP');
for(var i = 0; i < xmlHttpVersions.length && objXMLHttp == null; i++) {
try{
objXMLHttp = new ActiveXObject( xmlHttpVersions[i] );
} catch(e){
void(0);
}
}
}
if(objXMLHttp != undefined){
objXMLHttp.onreadystatechange = function() {
/*Your response handler here*/
}
}
To send a request to the server using either the 'POST' method or the 'GET' method:
if(strMethod == "POST"){
objXMLHttp.open(strMethod, strAddr, true);
objXMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
bjXMLHttp.send(strData);
} else {
objXMLHttp.open(strMethod, strAddr + strData, true);
objXMLHttp.send(null);
}
I would just write a function to convert your data object to a string formatted in the way send expects, namely "name1=value1&name2=value2".
function serialize (data) {
var result = "";
for (var key in data) {
result += (encodeURIComponent(key) + "=" + encodeURIComponent(data[key].toString()) + "&");
}
return result.substring(0, result.length - 1);
}
Then the final code becomes
function xhrRequest (data, method, url, callback) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.status == 200 && xhr.readyState == 4) {
callback(xhr.responseText);
} else {
callback("XHR Response Failed");
}
}
xhr.send(serialize(data));
}
It might also be good to consider XMLHttpRequest onload and onerror events as described here:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The readyState increments as the request is made so because you throw the error whenever readyState != 4 you'll always see your callback receiving the error, even if there is no error.
Check out this reference:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
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.
I have this function in my JavaScript function:
var xhr = new XMLHttpRequest();
var url = 'url';
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var str = xhr.responseText;
alert(str);
var resp = JSON.parse(str);
alert('12');
if (0 == resp.ErrorCode) {
alert('13');
}
}
}
xhr.send();
The str is always :
{"ErrorCode":0,"ErrorMessage":"OK","Command":"/api/getvideoinfo/","data":[{"VideoID":"ehcVomMexkY","IsInCache":true,"IsDownloading":false,"AvailableFormats":[{"DisplayName":"720","IsHD":true,"VidEncMimeType":"video/H264","AudEndMimeType":"audio/aac","Width":1280,"Height":720,"PlaybackURL":"","IsDefaultStream":false},{"DisplayName":"360","IsHD":false,"VidEncMimeType":"video/H264","AudEndMimeType":"audio/aac","Width":640,"Height":360,"PlaybackURL":"url","IsDefaultStream":true}]}]}
And i noticed that the script never get to :
alert('12');
Any idea what can cause this?Why the json won't parse? did i need to add any library to the html?
The url is the location of the file on the server. So the url variable should be the path from where you get the data which in this case should be
var url = "/api/getvideoinfo/";
while running these functions, I am calling such web service through which I have to generate session Id.
consider url is correct
I want to know,that I am calling function from onreadystatechange.wheteher it is correct way.
if you have another way please reply.
function getData(_url) {
var xmlhttpRequest = null;
xmlhttpRequest = new XMLHttpRequest();
xmlhttpRequest.open("GET", _url, true);
xmlhttpRequest.send();
xmlhttpRequest.onreadystatechange = function() {
//alert(xmlhttpRequest.status);
if(xmlhttpRequest.readyState == 4)// 4: The Request is complete
{
var request = xmlhttpRequest.responseXML;
var items = request.getElementsByTagName("id")[0].firstChild.nodeValue;
var hashcode = GetHashCode(passwordvalue + items);
var strUrl = commonURL + 'data/' + userName + ';' + hashcode;
data1(strUrl, 'tagname');//calling another function to generate session id
}
}
}
function data1(_url, _tagName)
{
var xmlhttpRequest = null;
xmlhttpRequest = new XMLHttpRequest();
xmlhttpRequest.open("GET", _url, true);
xmlhttpRequest.send();
xmlhttpRequest.onreadystatechange = function()
{
if(xmlhttpRequest.readyState == 4 && xmlhttpRequest.status==200)// 4: The Request is complete
{
var request = xmlhttpRequest.responseXML;
//alert('items .....= '+ request);
var sessionid = request.getElementsByTagName(_tagName)[0].firstChild.nodeValue;
alert('session ID='+sessionid);
}
}
}
Thanks,
i would place xmlhttpRequest.send(); after the onreadystatechange function
Also when you using the GET method you send a null value, that holds zero