Send PUT from pure Javascript to Laravel controller - javascript

i try to send data via PUT method, but Laravel 5.5 do not see any data inside Input (or Request) on destination controller.
Here JS:
function selectProject(option){
console.log('Update selected');
var data = new Object();
data.project_id = option.value;
data.user_id ={{auth()->user()->id}};
console.log(data);
var url = "/admin/projects";
var xhr = new XMLHttpRequest();
xhr.open("PUT", url+'/update_selected', true);
xhr.setRequestHeader("X-CSRF-TOKEN", "{{ csrf_token() }}");
xhr.onload = function () {
var response = xhr.responseText;
if (xhr.readyState == 4 && xhr.status == "200") {
console.log(response);
document.getElementById("app").innerHTML = response;
} else {
console.log(response);
document.getElementById("app").innerHTML = response;
}
}
xhr.send(data);
}
inside Laravel controller i try to showing inputs:
echo '[Controller]Inputs:';
return Input::all();
Here output from console.log:
Update selected
{…}
project_id: "4"
user_id: 1
__proto__: Object { … }
[Controller]Inputs:[]
Question: what i'am doing wrong and where is inputs data?
p.s. I can use only pure javascript, no jQuery or anothers.

Problem solved by adding header:
xhr.setRequestHeader("content-type", "application/json");
and wrapping data to JSON:
xhr.send(JSON.stringify(data));

Related

How can a Json return be sent from a controller to the frontend in Asp.NET Core MVC application?

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;
}
}
});
});

AttributeError: 'NoneType' object has no attribute 'get' //500 (Internal Server Error)

this is not sending any data from crome extension,i am trying to send json string to the server with mentioned url which says none type object has been returned,
var xhr = new XMLHttpRequest();
var ur = "http://127.0.0.1:8080/animal";
var dat = {"subject":"subject"};
xhr.open("POST", ur, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(dat);
}
};
xhr.send(dat);
You can't send an object with xhr.send(), you need to serialize it.
var dat = 'subject=subject';

can't pass post params to yii2 controller by xhr request

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);
})

HTTP error 400 in AJAX POST request

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

how to load json from url using javascript?

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.

Categories