Cannot access json data in component - javascript

I'm trying to get json data from a XMLHttpRequest and it works well so I see the data in the console. But the component which should show these data doesnt show any... Is there anything wrong? Maybe it's wrong to call the function in mounted()? I called it in created() too but nothing changed... Any ideas?
in script
data(){
return{
json: {}
}
}
mounted(){
var gsRef = firebase.storage().refFromURL('XXXXXXXXX')
gsRef.child(firebase.auth().currentUser.uid+'.json').getDownloadURL().then(function(url){
var xhr = new XMLHttpRequest()
xhr.responseType = 'json'
xhr.onload = function() {
this.json = xhr.response
console.log(this.json.user) //works shows the data!
}
xhr.open('GET',url)
xhr.send()
})
}
in template
<h1>{{json.user}}</h1> //doenst work. Cannot access data

"this" is probably referring to the wrong context (i.e. not the vue instance). Try saving a reference to the proper this before your firebase call, something like const self = this, and then use self.json to set the data.
mounted(){
var self = this
var gsRef = firebase.storage().refFromURL('XXXXXXXXX')
gsRef.child(firebase.auth().currentUser.uid+'.json').getDownloadURL().then(function(url){
var xhr = new XMLHttpRequest()
xhr.responseType = 'json'
xhr.onload = function() {
self.json = xhr.response
console.log(self.json.user) //works shows the data!
}
xhr.open('GET',url)
xhr.send()
})
}

Related

Monkey-patching XMLHttpRequest.send for special url

I'm trying to create an http-interceptor that will allow to add header to requests sent from within third-party app. I'm monkey-patching XMLHttpRequest.send
const origSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
this.setRequestHeader("A-Header", "Value");
return origSend.apply(this, [].slice.call(arguments));
};
The problem is that I don't need that header in other requests, still I don't see how can I access request url (to check if request is made from third-party lib). How can I make this interceptor work only in case there's a substring in url?
If you also monkey-patch the .open() method, you can store the passed url in the instance and read it later:
const origOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
this.url = arguments[1];
return origOpen.apply(this, [].slice.call(arguments));
};
const origSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
if (this.url) {
console.log("url found:", this.url);
this.setRequestHeader("A-Header", "Value");
}
// prevent error in snippet, uncomment next line
// return origSend.apply(this, [].slice.call(arguments));
};
const xhr = new XMLHttpRequest();
xhr.open("get", "https://stackoverflow.com");
xhr.send();

How to pass multiple parameters to #RequestBody using JavaScript XMLHttpRequest

I have that POST method:
function saveSchemaInDatabase(schemaName) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName);
}
and i am catching that shoot in my controller in that way:
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName) {
return "redirect:/user";
}
Can someone tell me how i can send multiple params to that controller? For example i want something like that:
//shoot
function saveSchemaInDatabase(schemaName, diagramJson) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
};
xhttp.open("POST", "/user/saveSchemaInDatabase", true);
xhttp.send(schemaName, diagramJson);
}
//catch
#PostMapping(path = { "/user/saveSchemaInDatabase" })
public String saveSchemaInDatabase(#RequestBody String schemaName, #RequestBody String diagramJson) {
return "redirect:/user";
}
I hope you know what i mean. Of course my way doesn't work. Error 400 appears.
Can someone help me? Im done :(
You can crete FormData object and add as many values as you want inside it
var data = new FormData();
data.append("email", "eve.holt#reqres.in");
data.append("password", "pistol");
Then send this formData object to the post request
Like this
xhttp.send(data);

Fetch api get call to PHP endpoint that returns JSON object fails but regular XHR works?

I have a PHP endpoint that returns a JSON-object (maybe that is not what this is?)
{"my_array":["a","b","c","d"]}
That's what you see when you view that page. It's created using
$array = [];
$array['my_array'] = ["a","b","c","d"];
echo json_encode($array);
When I use a regular XHR call from MDN
// get XHR from MDN
function getAjax(url, success) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) success(xhr.responseText);
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
return xhr;
}
I can iterate over it using this post-call function:
getAjax('get-users.php', logOutput);
function logOutput(response) {
console.log(JSON.parse(response));
// returns: {"my_array":["a","b","c","d"]}
}
When I try to do this with fetch, it doesn't work.
fetch('get-users.php')
.then((res) => {
return res.json(); // also tried res.text();
})
.then((data) => {
console.log(data);
});
I'm not sure if the way I'm creating the output from PHP is wrong, or if my Fetch is wrong.
Here is an image of the code/console.log
Edit: I wanted to point out it's not a url/target problem, for the sake of site anonymity I whited out some parts of the link.

Laravel: $request->all() gives empty array when called with json xhr

For some reason I cannot use $.ajax, only the XMLHttpRequest.
I need to send json to laravel controller. When I tried it, I only got 500s
Here's how I make the request:
const sendEdit = function(){
let xhr = new XMLHttpRequest();
xhr.open("POST", "/blog/edit");
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'))
let data = {};
data.header = $("#editHeader").val();
data.body = $("#editBody").val();
data.postId = {{$post->id}};
data.userId = {{Auth::user()->id}}
xhr.onreadystatechange = function(d){
}
xhr.send([data]);
}
The controller returned 500. When I tried to var_dump $request->json() or $request->all() it showed me an error. Here's my controller. Please help me access the data in JSON
public function edit(Request $request){
echo(var_dump($request->all()));
}
The problem was not using JSON.stringify() before sending the request.

Empty response when pushing arrays to JSON

I can't figure out why my multidimensional array in JSON always is empty in the response. If I declare my JSON static like this..
var data = {
foo: 123,
bar: 456,
cars: [
{ name:"Ford", test: 4},
{ name:"BMW" },
{ name:"Fiat"}
]
};
Response:
(index):78 Success
(index):79 {"foo":123,"bar":456,"cars":[{"name":"Ford","test":4},{"name":"BMW"},{"name":"Fiat"}]}
So this works, but when I add arrays dynamically the response is empty..
var data = {
foo: 123,
bar: 456,
};
data.cars: [];
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
document.onmousemove=function(e) {
var mousePos = getMousePos(e);
data.cars.push({x: mousePos.x, y: mousePos.y});
console.log(JSON.stringify(data));
};
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'http://localhost:80/t';
var method = 'POST';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
console.log("Success");
console.log(xhr.responseText);
};
xhr.onerror = function() {
console.log("Error");
};
xhr.send(JSON.stringify(data));
The console before I send..
{"foo":123,"bar":456,"cars":[{"x":320,"y":8},{"x":321,"y":20}]}
The response I get..
(index):79 Success
(index):80 {"foo":123,"bar":456,"cars":[]}
The "cars" array always ends up empty in the response when I push arrays to the JSON string. I have read every stackoverflow thread I can find about this but can't figure out the problem.
Response code on server
public function getJson(Request $request) {
$content = $request->json()->all();
return $content;
}
I should also point out that i'm using Laravel 5.4 on the response server.
I could see 2 mistakes:
Define Cars object like data.cars = []; rather using data.cars: [];
Ajax calls are asynchronous in nature, based on the code which you have written xhr.send will be called before document.onmousemove function.
onmousemove requires mousemove event to trigger but xhr.send is not inside any function and hence getting called as soon as page is getting loaded.
So you will have to make 2 changes:
Define Cars object like data.cars = [];
Call xhr.send method after assignment of data in mousemove function i.e. inside mousemove or other function

Categories

Resources