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

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.

Related

I want to receive a JSON (sendend by POST method of JS xmlHttpRequest()) echo from PHP

The code JS is
var xhr = new XMLHttpRequest()
//console.log(xhr)
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
console.log(xhr)
}
}
xhr.open("POST","https://testepr.harpiastudios.com.br/http-receiver.php")
xhr.setRequestHeader('Content-Type', 'application/json')
function sendText(text){
let dataToSend = {
"text": text
}
console.log(dataToSend)
xhr.send(dataToSend)
}
and the PHP Code is:
$dataToSend = json_decode(file_get_contents('php://input'));
echo($dataToSend->text);
The php file returns
Notice: Trying to get property of non-object in
I need to echo this value cause i need to use for other things. I dont know to have acces from this index of JSON

Ajax send JSON object with two arrays to a servlet and parsing in java servlet without jQuery

I have to send to a servlet two arrays, i use an Ajax POST call that sends a JSON object, and then I have to read the data sent in two lists or arrays in a servlet class in java.
I prefer not to use jQuery for Ajax call.
I am not very familiar with json, i used some code found in stackoverflow and i can't understand if there is a problem in sending or parsing data.
Here is the method to make the Ajax call in Javascript, where cback is the callback function, method = "POST" and url is the url of the servlet:
function makeCall(method, url, from, to, cback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
cback(req)
};
req.open(method, url);
var obj = {};
obj["from"] = from;
obj["to"] = to;
var data = JSON.stringify(obj);
req.send(data);
}
Here is the doPost method in the servlet controller specified by the url. Here is where i found the problem: after doing getParameter, strings json1 and json2 are null:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//...
String json1 = request.getParameter("from");
String json2 = request.getParameter("to");
Gson gson = new Gson();
ArrayList<Double> listFrom = gson.fromJson(json1,
new TypeToken<ArrayList<Categoria>>() {}.getType());
ArrayList<Double> listTo = gson.fromJson(json2,
new TypeToken<ArrayList<Double>>() {}.getType());
//...
}
Your ajax is sending JSON but your servelet is expecting form data, that has JSON in it.
To send the data like your server expects encode each array to JSON and send them as form data
function makeCall(method, url, from, to, cback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
cback(req)
};
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.open(method, url);
var params = new URLSearchParams({to: JSON.stringify(to), from: JSON.stringify(from)});
req.send(params.toString());
}

Correct content-type for sending this AJAX Post data

I am having problem sending base64 image data using ajax post
I think I have the wrong value for Content-Type but have tried application/json, text/json and image/jpeg without any success
Javascript
function sendFormData(fD)
{
var urls = fD.get('urls');
console.log('urls', urls);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
alert(urls);
xhr.setRequestHeader("Content-type", "image/jpeg");
xhr.send(urls);
}
Browser console shows
["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUTExMWFhUXGRgbGBgXGR0aGRgXHRgYFx4YGxkYHiogGh4lGxgdIjEhJSkrLi4uGh8zODMtNygtLisBCgoKDg0OGhAQGy0lHSUtLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIANEA8QMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQMGAAECBwj/xABGEAACAQIEBAQDBAUJCAIDAAABAhEDIQAEEjEFIkFREzJhcQaBkRRCobEjUsHh8AcVM2JygsLR8RZDRFNzg5KyJDSzw8T/xAAZAQADAQEBAAAAAAAAAAAAAAABAgMABAX/xAAqEQACAgEDBQACAQQDAAAAAAAAAQIRAxIhMQQTFEFRImGRYnGh8AUjMv/aAAwDAQACEQMRAD8AsoosJt9cSpSdeYKYEXxKlQs4E2kEx6dMWJFBEDr0OPey5nCrR58MalwJUpB1nENbJWthpTyQDG5H5Y0gGqNQOJLLXA7h9K9VypGITSPbD+tSGIFy4mSJx0xz7EXjE7UscacNamW30jAlbLsNxiscqZNwoCK4wDEzJjkLiuoQjGNEYnCY5ZcawkMY5bEkY5GGsUijG1XtjcYPyFAQWMbbdsac9Ks0Y2wQphlwTKLUZg2wAwFmq8m5HYY5HFTRph0VnBI1QDZZgsZGwEnHPmn/ANb+lMcVqLFWRafKMTU+L6bRb88V/LcY+0otQKVmbdcbq1wsSYkgDfc7C3fHIoRlDVIs5tSpFzyXEtcdCdvlhopwp4RSpwvcAf64bj0x5mbSpUjrhdbmicSU1xi08djEWylGRjRGOsC5uodl379sBK2F8HbMAJxUON5lqrQFMA4f1CVU62ke2FaZlWqXgAbepx29MtD1VZzZXaol4RwYKsuAWP4…
Java Server code
public String updateArtwork(Request request, Response response)
{
System.out.println("Received artwork");
for(String s:request.queryParams())
{
System.out.println("---"+s);
}
System.out.println("ReadParms");
return "";
}
just outputs
Received artwork
ReadParms
Updated to Send as Form Instead
// Once we got everything, time to retrieve our objects
function sendData()
{
var fD = new FormData();
// send Files data directly
var files = imgList.filter(
function isFile(obj)
{
return obj.type === 'file';
}
);
files.forEach(
function appendToFD(obj)
{
fD.append('files[]', obj.file);
}
);
// for elems, we will need to grab the data from the server
var elems = imgList.filter(
function isElem(obj)
{
return obj.type === "element";
}
);
var urls = elems.map(
function grabURL(obj)
{
return obj.element.src;
}
);
if (urls.length)
fD.append('urls', JSON.stringify(urls));
sendFormData(fD);
};
function sendFormData(fD)
{
// but here we will just log the formData's content
var files = fD.getAll('files[]');
console.log('files: ', files);
var urls = fD.get('urls');
console.log('urls', urls);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(fD);
}
then on server I have
public String updateArtwork(Request request, Response response)
{
System.out.println("Received artwork");
for(String s:request.queryParams())
{
System.out.println("***"+s);
System.out.println(request.queryParams(s));
}
System.out.println("ReadParms");
return "";
}
and its outputs
Received artwork
***-----------------------------330219842643
Content-Disposition: form-data; name
"urls"
["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMSEhUSExIWFhUXFxgXGBcYFRgXFxkdGBcWGBgYFx0YHSggHR0lHRkYITEhJSkrLi4uFyA1ODMtNygtLisBCgoKDg0OFQ8PFSsZFRkrLSstLSstKysrLS03KystLSstKy03LSstLSstNzc3KysrLS0tKysrKysrKysrKysrK//AABEIAKoBKQMBIgACEQEDEQH...."]
-----------------------------330219842643--
ReadParms
So I'm now getting the data but I don't understand really understand how to parse the Content-Disposition part in Java.
This code wasn't originally written by me, as you can see the FormData is constructed it doesnt come from an actual form. My first attempt was to try and extract from FormData and send in different way, an alternative would be to not store in FormData in the first place but dont know how to do this.
Update 2
Tried just sending first url rather than formdata or an arrya of urls, because actually there is only ever one url.But it just doesnt work, nothing received by server ?
function sendFormData(urls)
{
console.log('urls', urls[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/editsongs.update_artwork');
xhr.setRequestHeader("Content-type", "text/json");
alert(JSON.stringify(urls[0]));
xhr.send(JSON.stringify(urls[0]));
}
You are trying to view data in the body using queryParams(), which will give you the query params that are located in the url.
Load data from the request body using body().

Tableau REST API: Using Javascript to get the Token

I am a complete beginner with REST API and I could not figure out how I am to proceed.
I installed Postman and was successfully able to get the Token, but I am not sure how to send the raw XML payload in javascript.
<tsRequest>
<credentials name ="XXX" password="YYY" >
<site contenturl = "" />
</credentials>
</tsRequest>
I have :
httpRequest.open('POST', 'http://MY-SERVER/api/2.4/auth/signin', false);
httpRequest.setRequestHeader("Content-type", "application/xml");
Not sure how to add the xml payload. I have access to a Tableau Server(MY-SERVER) and everything.
Any help would be greatly appreciated!
Thank you!
You are getting closer, you just need to use the send method to send your XML: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
Just make sure that your XML is properly encoded in javascript when you're inputting it. So if you are using double quotes inside your XML, make sure you have single quotes to declare your string in javascript (e.g.) var data = '<credentials name="XXX" >';
Related: Send POST data using XMLHttpRequest
In addition to #AnilRedshift answer, here's the functioning code:
login_details=[];
function getToken() {
var url = "http://yourServerAddress/api/2.0/auth/signin";
var params = "<tsRequest><credentials name='Username' password='UserPassword' ><site contentUrl='' /></credentials></tsRequest>";
return zuo = new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.withCredentials = true;
xhr.onload= function(){
if (this.status === 200) {
var parsed_xml = JSON.parse(JSON.stringify(x2js.xml_str2json(xhr.responseText)))
login_details.push(parsed_xml.tsResponse.credentials._token); login_details.push(parsed_xml.tsResponse.credentials.site._id);
resolve(login_details);
}
}
xhr.onerror=reject;
xhr.send();
})
}
function getWorkbooks(){
var url = "http://serveraddress//api/2.3/sites/"+login_details[1]+"/workbooks?pageSize=1000";
return zuo = new Promise(function(resolve,reject){
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("X-Tableau-Auth",login_details[0]);
xhr.onload= function(){
if (this.status === 200) {
var workbooks = JSON.parse(JSON.stringify(x2js.xml_str2json(xhr.responseText)))
for (var f=0;f<workbooks.tsResponse.workbooks.workbook.length;f++){
if(workbooks.tsResponse.workbooks.workbook[f].project._name=="Default"){
workbooks_list.push(workbooks.tsResponse.workbooks.workbook[f]._id)
}
resolve();
}
}
}
xhr.onerror= function(){
console.log(xhr.responseText);
}
xhr.send();
})
}
Invoke the code with:
getToken()
.then(function(login_details){
console.log(login_details[0]+"/"+login_details[1]);
})
.then(function(){
getWorkbooks();
})
getToken() function gets the login token which has to be used in all subsequent calls.
getWorkbooks() fetches all dashboards in 'Default' project but this kind of request can be used for all GET type requests.
Please note that this approach uses hardcoded values for password and username which is generally not the best practice. It would be way better to use server side scripting or encrypting (better but still with flavs).
You can find whole step by step tutorial and running code here:
http://meowbi.com/2017/10/23/tableau-fields-definition-undocumented-api/

XMLHttpRequest send JS Object

I'm trying to send an JS Object with an (POST) XMLHttpRequest, but I get no POST data in PHP.
This code worked before with an Ajax request, but i'm trying to get feedback from the server for an progressbar ( whitch is working fine now). That's why i've chagend to XMLHttpRequest.
The code:
var dataRows = {
'bewaarnaam': bewaarNaam,
rows: {}
};
$(".rows").each(function (i, obj) {
var row = $(obj);
var rowName = $(row).attr('name');
var chests = {};
$(".cv_chest", row).each(function (i2, obj2) {
chests[$(obj2).attr('id')] = {
'counter': $(obj2).attr('chest_counter'),
'height': $(obj2).attr('chest_height'),
'db_id': $(obj2).attr('db_id')
};
});
var top = $(row).css('top').replace("px", "");
var left = $(row).css('left').replace("px", "");
var rowData = {
'name': $(row).attr('name'),
'x': parseInt(left),
'y': (parseInt(top - 100)),
'rotation': rotation[$(row).attr('dir')],
'db_id': $(row).attr("db_id"),
'chests': chests
};
dataRows.rows[$(row).attr('id')] = rowData;
});
...
var xhr = new XMLHttpRequest();
xhr.open("POST", "{{ url('bewaarplaatsen/xhrTest/') }}", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(dataRows);
So my question is rather simple... How can i send an object with an post through the XmlHttpRequest function?
Use JSON:
var xhr = new XMLHttpRequest();
xhr.open("POST", "{{ url('bewaarplaatsen/xhrTest/') }}", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(JSON.stringify(dataRows));
EDIT:
You can also use newer fetch API, see Fetch: POST JSON data.
You can't. "An object" is a data structure that exists in memory and only makes sense to the program it is dealing with it.
You need to serialise the data (e.g. using the application/x-www-form-urlencoded format, or JSON, or XML, or a host of other choices) and send that instead.
If you are trying to send entire DOM elements (and it isn't clear what the data you are trying to send actually is) then serialising them would involve converting them to HTML or (and this would usually be the better option) a data structure that they represent.

Categories

Resources