I would like to send an array with elements to my laravel controller with vanilla JS, (I don't want to use Jquery). But I can't get it work... I found several solutions on web with trying to make a json object and so on but nothing wanted to work...
This is my code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('sent');
}
};
xhttp.open("GET", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.send(categories);
and my laravel controller:
public function toggleCategory(Request $request, User $user)
{
dd($categories = $request->categories);
$user->categories()->sync(collect($categories));
}
I changed a few things and now it is working!
The working code:
web.php:
Route::post('{user}/togglecategory', 'Site\ProfileController#toggleCategory')->name('toggleCategory');
Javascript code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('send');
}
};
xhttp.open("POST", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
xhttp.send("categories="+categories);
});
Laravel Controller:
public function toggleCategory(Request $request, User $user)
{
$categories = explode(',', $request->categories);
$user->categories()->sync($categories);
}
Related
I wanted to know how to add parameters into HttpContext.Request.Form via client side so that in the serve side i can get these data
i don't want to use ajax.
I tried the following but with no success:
javascript code:
var request = new XMLHttpRequest();
request.open("POST", window.location.host, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.append('skip', '10');
request.send(formData);
the asp.net mvc line of code:
var a = HttpContext.Request.Form.GetValues("skip");
but a is equal to null.
thank you all
Update:
I want to do something like datatable. In datatbles you can set draw,start, col_order etc. And you can get it with request into the server side. I want to know how can i do something like that.
You will need to combine data like this - "key1=value1&key2=value2&skip=10".
View
<button type="button" onclick="postData()">Post data</button>
<div id="result"></div>
<script>
function postData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("POST", "#Url.Action("PostData", "Home")", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("key1=value1&key2=value2&skip=10");
}
</script>
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult PostData(FormCollection collection)
{
var key1 = collection["key1"];
var key2 = collection["key2"];
var skip = collection["skip"];
return Json($"key1: {key1}, key2: {key2}, skip: {skip}");
}
}
Screen Shots
I have a PHP script which queries a database and returns a table, depending on the input, e.g.results.php?f=1.
I am trying to call it multiple times from JavaScript:
function go(n,divid) {
document.getElementById(divid).innerHTML = "<img src=\"load.gif\">";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(divid).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", n, true);
xmlhttp.send();
}
Call later
go('results.php?print=1&nh=1','d1');
go('results.php?print=2&nh=1','d2');
go('results.php?print=3&nh=1','d3');
go('results.php?print=4&nh=1','d4');
The PHP code connects to a SQLite3 database. The problem with the above is that sometimes it works, but sometimes one of the queries fails to be prepared by SQLite3::prepare().
What could be wrong? A sqlite race condition? A javascript issue?
When results.php is called just once, the query always succeeds.
Thanks.
Use xhttp instead of xmlhttp.
function go(n,divid) {
var xhttp = new XMLHttpRequest();
document.getElementById(divid).innerHTML = "<img src=\"load.gif\">";
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(divid).innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", n, true);
xhttp.send();
}
go('results.php?print=1&nh=1','d1');
I am trying to send a form data using POST method and xmlhttp.open
Please help find the error in my code
function submitChat() {
if (form1.msg.value == '' ) {
alert ('ALL FIELDS ARE MANDATORY');
return;
}
var xmlhttp = new XMLHttpRequest();
var msg = form1.msg.value;
var params = 'msg=helloooooooo';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('POST', 'rtest.php?rid=14', true);
xmlhttp.send(params);
}
Everything is fine and it is working with GET method. but POST method is not working. Please help.
I need to get some JSON data from and AJAX function in PHP
This is what i've written so far but not sure exactly what to do on the PHP side.
JS:
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(json);
}
PHP:
<?php
if(isset($_POST['json']) ){
$json = $_POST ['json'];
$json_d = json_decode($json);
echo $json . 'hello';
} else {
echo 'error';
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src='ajax.js'></script>
<body>
HELLO THERE THIS IS AN HTML PAGEEEEE
</body>
</html>
Stringify your JSON on the client side.
window.onload = function() {
var json = {
hello : 'howareyou',
good : 'yes i am good',
toast : 'i love toast'
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
} else {
alert("no");
}
}
xhr.open('POST', 'json.php', true);
xhr.send(JSON.stringify(json));
}
Decode the JSON from the raw request body.
$json = json_decode(file_get_contents("php://input"));
If you want to use raw post data, to get JSON try:
$json = json_decode(file_get_contents("php://input"));
JS example:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({key:"value", key:"value"}));
I am new to symfony2. Basically I want to send a variable name to a file named sub.html.php. I am making an ajax request as following :
function onsub()
{
alert(document.getElementById('source').value);
var http=new XMLHttpRequest();
var name="rohit";
http.open("POST", {{path('task1')}}, false);
http.onreadystatechange = function()
{
alert(http.status);
if(http.readyState == 4 && http.status == 200)
{
alert('i m back');
}
else
{
alert('sorry');
}
}
http.send();
return false;
}
I have defined the route of task1 as follow:
task1:
pattern: /task1/
defaults: {_controller:AcmeTaskBundle:Task:task1}
and in TaskController I have defined task1Action as follow:
public function task1Action()
{
return $this->render('AcmeTaskBundle:Default:sub.html.php');
}
but I am unable to call the sub.html.php file anyhow. How can I call this file?
You can forward the request from the TaskController::task1Action() like so...
$response = $this->forward('VendorOtherBundleName:ControllerName:ActionName', array(
'some_variable' => $value
));
You can read more here