TokenMismatchException in laravel 5.2 ajax call - javascript

i am getting token mismatch exception every thing is seem correct.
this is my view code
#extends('layouts.master')
#section('content')
<div class="bg"></div>
<div class="login-sec clearfix">
<h1 class="lg-logo">YOU ARE JUST ONE STEP AHEAD</h1>
<div class="login-box clear">
<form id="websiteform" action="#">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="col-md-12 form-field">
<label for="">Project Name</label>
<input type="text" name="project" id="project">
</div>
<div class="col-md-12 form-field">
<label for="">Website URL</label>
<input type="url" name="website_url" id="website_url">
</div>
<div class="col-md-12 form-field">
<button type="submit" class="btn-green btn-large">Add Your Website</button>
</div>
</form>
</div>
</div>
#stop
and form source head section and footer is
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="csrf-token" content="4ryCSznz0mPSBcwXvbmZZHkZGcxZpyDy2dQ1VAoc" />
<link href="http://localhost:8080/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="http://localhost:8080/js/jquery.min.js"></script>
<script src="http://localhost:8080/js/bootstrap.min.js"></script>
<script src="http://localhost:8080/js/main.js"></script>
and my ajax call in main.js
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#websiteform').submit(function(e){
e.preventDefault();
var pro=$('#project').val();
var url=$('#website_url').val();
$.ajax({
type: "POST",
url: "project_save",
data: {project: pro, url: url},
success: function(data)
{
if(data.success==false)
{
alert(data.error);
}
else{
window.location = "dashboard";
}
},
error:function(){}
});
});
});
and route and controller function
Route::post('/project_save','WebsiteController#project_save');
public function project_save()
{
if(Request::ajax()){
$validator = Validator::make(Request::all(), [
'project' => 'required|max:255',
'url' => 'required',
]);
if($validator->fails()){
return Response::json(['success'=>false,'error'=>$validator->errors()->toArray()]);
}
$Website = new Website;
$Website->project_name = Request::get('project');
$Website->website_url = Request::get('url');
$Website->user_id = Auth::id();
$Website->save();
return Response::json(['success'=>true]);
}
}
this is my code and i am getting tokenmismatach exeption.

Change your \App\Http\Middleware\VerifyCsrfToken.php, add this code to function tokensMatch:
if ($request->ajax()) {
return true;
}

If you do not want CSRF protection for a particular url then you can add the urls in App\Http\Middleware\VerifyCsrfToken.php like this
protected $except = [
"project_save"
];

Try this
$_token = "{{ csrf_token() }}";
$.post( 'myurl', { param1: $param1, param2: $param2, _token: $_token })
.done(function( data )
{
console.log('Done!');
});

Carefully do a check on the following :
I had a similar issue and it was an easy fix.
Add this in your HTML meta tag area :
<meta name="csrf-token" content="{{ csrf_token() }}">
Then under your JQuery reference, add this code :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
If you are using the HTML form submit (not AJAX) then you need to put :
{{ csrf_field() }}
inside your form tags.

Related

Using RedirectToAction but control stays in same page

Here is my Index page code i.e. JS code I am able to jump on controller action method i.e. URL: '/UserAccount/Login' but in Login action method I am redirecting to other pages..but controls remain on the same page
enter code here
<script type="text/javascript">
function UserLogin() {
var username = $("#txtUsername").val();
var passcode = $("#txtPassword").val();
$.ajax({
url: '/UserAccount/Login',
type: "POST",
data: { 'username': username, 'passcode': passcode },
dataType : 'json',
traditional: true,
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data.username);
}
});
};
</script>
[HttpPost]
public ActionResult Login(string username, string passcode)
{
if (IsValidUser(username, passcode))
{
MaintainLoginDetails(username);
return RedirectToAction("AdminDashboard");
}
else
{
ModelState.AddModelError("", "Your Username or password is invalid");
return View();
}
}
public ActionResult AdminDashboard()
{
return View();
}
As suggested i have added my view code below.I have created login page here.on button click i am calling controller action method and on action i wanted to redirect to another action/view.
#model Spark.Models.Users
#{
ViewData["Title"] = "Home Page";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login Here</title>
<link rel="stylesheet" type="text/css" href="~/css/login.css" />
<script src="~/lib/jquery/dist/jquery.js" type="text/javascript"></script>
<script src="~/lib/jquery/dist/jquery.min.js" type="text/javascript"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
function UserLogin() {
var username = $("#txtUsername").val();
var passcode = $("#txtPassword").val();
//$.post("/UserAccount/Login", { username, passcode }, function (data) {
// alert(data);
//});
$.ajax({
url: '/UserAccount/Login',
type: "POST",
data: { 'username': username, 'passcode': passcode },
dataType: 'json',
traditional: true,
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data.username);
}
});
};
</script>
</head>
<body>
<div id="login">
<div class="nlite_logo">
<ul>
<li><img src="~/images/login.png" width="107" height="50" alt="" /></li>
</ul>
</div>
<form action="">
<fieldset>
<div><input type="text" id="txtUsername" required value="Username" onBlur="if(this.value=='')this.value='Username'" onFocus="if(this.value=='Username')this.value='' "></div>
<div><input type="password" id="txtPassword" required value="Password" onBlur="if(this.value=='')this.value='Password'" onFocus="if(this.value=='Password')this.value='' "></div>
<div><input type="submit" value="Login" class="login_Button_Btn" onclick="UserLogin()"></div>
</fieldset>
</form>
</div>
</body>
</html>
Below is work demo, you can refer to it.
In RedirectController, change your return method to Json .
public class RedirectController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Login(string username, string passcode)
{
//do your staff...
return Json(new { redirectToUrl = Url.Action("Privacy", "Redirect") });
}
public IActionResult Privacy()
{
return View();
}
}
In Index view,in Ajax call use "window.location.href = response.redirectToUrl;" to redirect to a specific page in success method.
<div class="row">
<div class="col-md-4">
<form id="myform" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label">username</label>
<input id="txtUsername" name="username" class="form-control" />
</div>
<div class="form-group">
<label class="control-label">passcode</label>
<input id="txtPassword" name="passcode" class="form-control" />
</div>
<div class="form-group">
<input type="button" id="update" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#section Scripts
{
<script>
var update = $('#update');
update.click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// Get form
var form = $('#myform')[0];
// Create an FormData object
var formData = new FormData(form);
$.ajax({
url: '/Redirect/Login',
data: formData,
contentType: false,
processData: false,
type: 'POST',
success: function (response) {
window.location.href = response.redirectToUrl;
}
//success: function (result) {
// alert(result);
});
});
</script>
}
Result:

pass a string from ajax function to spring controller

I'm working on a standalone application and I'm trying to pass a string which is an output of change event, to the spring controller using the code below
HTML CODE
<!DOCTYPE HTML>
<html xmnls:th="http://www.thymeleaf.org">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<title>ADD NEW BILL</title>
<!-- jquery -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$("#Mandy_Name").autocomplete({
source: "autocomplete",
minLength: 3
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#Mandy_Name").change(function(){
var changed = $(this).val();
console.log(changed);
$.ajax({
type : "POST",
dataType : 'json',
url : "mandyname",
data: {name:changed},
success: function(data) {
console.log(data);
return false;
}
});
});
});
</script>
</head>
<body>
<div class="container">
<hr>
<p class="h4 mb-4">SAVE NEW PURCHASE BILL</p>
<form action="#" th:action="#{/savePurchase}"
th:object="${purchase}" method="post">
<!-- add a hidden field to handle update -->
<!-- <input type="hidden" th:field="*{idPurchaseDetails}"> -->
<input type="hidden" th:field="*{ID}">
MANDY NAME : <input id="Mandy_Name" type="text" th:field="*{mandyName}"
class="form-control mb-4 col-4" placeholder="Mandy Name">
GSTIN : <input type="text" th:field="*{gstin}"
class="form-control mb-4 col-4" value = gst() placeholder="GSTIN">
<button type="submit" class="btn btn-info col-2">SAVE</button>
</form>
<br><br>
<a th:href="#{/purchaselist}">BACK TO PURCHASE LIST</a>
</div>
</body>
</html>
controller code
#RequestMapping(value = "mandyName", method = RequestMethod.POST)
public ModelAndView getSearchResultViaAjax(#RequestBody Purchase purchase, HttpServletRequest request,
HttpServletResponse response)
{
ModelAndView mv = new ModelAndView();
String name = purchase.getMandyName();
System.out.println(name);
return mv;
}
I'm getting an error "Failed to load resource: the server responded with a status of 404 ()" in the browser console.
Help me to pass the string "changed" to the controller.
I'm using these dependencies
jquery from "org.webjars" ,
spring-boot-starter-actuator ,
spring-boot-starter-data-jpa ,
spring-boot-starter-web ,
spring-boot-starter-data-rest ,
spring-boot-starter-thymeleaf ,
spring-boot-devtools ,
spring-boot-starter-json ,
mysql-connector-java ,
spring-boot-starter-test ,
junit-vintage-engine ,
spring-boot-maven-plugin
Should I be using any other dependencies ??
The HTTP Status 404 means that the URL provided, cannot be found on the server.
I see that you make the Ajax call with an incorrect URL. Change it to the correct one depending on your Spring App and port.
Normally it should be under: http://localhost:8080/mandyName. But this you have to check and examine.
Sample JS code:
$(document).ready(function(){
$("#Mandy_Name").change(function(){
var changed = $(this).val();
console.log(changed);
$.ajax({
type : "POST",
dataType : 'json',
url : "http://localhost:8080/mandyName", // ~~ HERE ~~
data: {name:changed},
success: function(data) {
console.log(data);
return false;
}
});
});
});

Missing required parameters for [Route: sender] [URI: {name}/{code}] [Missing parameters: name, code]

This may seem duplicate but I have this problem using AJAX and I don't know how to fix it.
Routes: web.php
Route::get('/{name}/{code}', 'TestController#counter');
Route::post('/{name}/{code}', 'TestController#sender')->name('sender');
Controller: TestController.php
public function counter() {
return view('room');
}
public function sender(Request $request) {
$xd = array(
'1' => request('text'),
'2' => Request::url()
);
event(new TestEvent($xd));
}
View: room.blade.php:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>
<form>
#csrf
<label for="lname">Code:</label><br>
<input type="text" id="text" name="text"><br><br>
<input type="submit" value="Submit">
</form>
</div>
<script type="text/javascript">
$("form").on("submit", function (e) {
var data = $(this).serialize();
$.ajax({
type: "POST",
URL: "{{ route('sender') }}",
data: data,
success: function () {
console.log("works");
}
});
e.preventDefault();
});
</script>
</body>
</html>
The error is the AJAX if I take it out I don't get an error. The AJAX code is to call the Controller without redirecting to another page. Any idea how to fix it?
Use This Route:
Routes: web.php
Route::get('', 'TestController#counter');
Route::post('', 'TestController#sender')->name('sender');
If you want to send a parameter, then define your parameter in your route, like below:
Routes: web.php
Route::get('/{name}/{code}', 'TestController#counter');
Route::post('/{name}/{code}', 'TestController#sender')->name('sender');
Controller: TestController.php
public function counter($name, $code) {
//---Note: Use $name and $code in your method
return view('room', compact('name', $code));
}
public function sender(Request $request, $name, $code) {
//---Note: Use Those parameters in your method
$xd = array(
'1' => request('text'),
'2' => Request::url()
);
event(new TestEvent($xd));
}
View: room.blade.php:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div>
<form>
#csrf
<label for="lname">Code:</label><br>
<input type="text" id="text" name="text">
<br />
<br />
<input type="submit" value="Submit">
</form>
</div>
<script type="text/javascript">
$("form").on("submit", function (e) {
var data = $(this).serialize();
$.ajax({
type: "POST",
URL: "{{ route('sender', ['name' => '', 'code' => '']) }}",
data: data,
success: function () {
console.log("works");
}
});
e.preventDefault();
});
</script>
</body>
</html>

why when i reload a page using AJAX the data disappears

Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>

why it doesn't display "you had wrong" message?

Often i use ajax by jquery but according to the below code why it doesn't display "you had wrong" message when "IF"is true? and just display "faile" message?
file Login.php
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<title>just for test</title>
</head>
<div id="Response" ></div>
<h3>login</h3>
<form id="Login" class="form-login">
<input type="text" class="form-control" name="yourname" id="yourname" placeholder="yourname">
<button type="submit" class="btn btn-bricky pull-left"> ورود <i class="fa fa-arrow-circle-right"></i> </button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function (e){
$("#Login").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "include/php/check_login.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
if(data=='faile'){
$("#Response").html('you had wrong...');
}else{
$("#Response").html(data);
}
return false;
}
});
}));
});
</script>
</body><!-- end: BODY -->
</html>
file:check_login.php
<?php
if (isset($_POST['yourname']) && !empty($_POST['yourname']))
{
$yourname=$_POST['yourname'];
echo $yourname;
}
else echo "faile";
?>
Here is method for receiving json based data
<!DOCTYPE html>
<html lang="en" class="no-js"> <head> <title>just for test</title> </head>
<body>
<div id="Response" ></div>
<h3>login</h3>
<form id="Login" class="form-login">
<input type="text" class="form-control" name="yourname" id="yourname" placeholder="yourname">
<button type="submit" class="btn btn-bricky pull-left"> ورود <i class="fa fa-arrow-circle-right"></i> </button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
$(function (e) {
$("#Login").submit(function(e){
e.preventDefault();
$.ajax({
url: "check_login.php",
data: new FormData(this),
type: "POST",
contentType: false,
cache: false,
processData:false,
// data type should be set to json to get the response data as json value
dataType: 'json',
success: function(json) {
if( json.data == 'faile') {
$("#Response").html('you had wrong...');
} else {
$("#Response").html(json.data);
}
return false;
}
});
});
});
</script>
</body>
</html>
check_login.php
<?php
session_start();
if (isset($_POST['yourname']) && !empty($_POST['yourname']))
{
$response = array( "data" => $_POST['yourname']);
} else {$response = array( "data" => "faile");}
echo json_encode($response);
?>
Using json, there should be no error regarding \n :: the new line after echo
Place
var yourname=$('#yourname').val();
between <script> and $(document).ready(function (e){
and change from
data: new FormData(this),
to
data: "yourname="+yourname;
add die(); after else echo "faile";
Look for newline that is returned after the ?>, as it returns something like "faile\n".
You can use one of:
remove the closing ?> tag
add die after echo
check for "faile\n"(not recommended)

Categories

Resources