VerifyCsrfToken Exception on form submit after AJAX response - javascript

I have AJAX action which renders a form which contains several input fields and submit button.
This is AJAX call:
<script type="text/javascript">
$('#call_filter').click(function() {
$.ajax({
url : 'brandSpendingsFilter',
type: 'POST',
data: {company: $('#company').val(), country: $('#country').val(), dateFrom: $('#dateFrom').val(), dateUntil: $('#dateUntil').val(), media: $('#media').val(),
products: $('[id^=products_]').serialize()},
beforeSend: function() {$('#search_result').empty(); $("#loading-image2").show(); },
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
},
success : function(data) {
$("#loading-image2").hide();
$('#search_result').append(data);
}
});
});
</script>
And my form:
{!! Form::open(['url' => 'brandSpendingsCSV', 'method' => 'POST', 'id' => 'csv']) !!}
{{ csrf_field() }}
<input type="hidden" name="campaignID" value="#foreach($campaignID as $c){{$c}},#endforeach">
<input type="hidden" name="dateFrom" value="{{$dateFrom}}">
<input type="hidden" name="dateUntil" value="{{$dateUntil}}">
<input type="hidden" name="media" value="{{$media}}">
<input type="hidden" name="country" value="{{$country}}">
</tr>
</table>
#if(Auth::user()->isAdmin())
<div class="row" style="float: right;"><button type="submit" onclick="submitForm()" class="btn btn-warning">CSV EXPORT</button></div>
#endif
<br>
<br>
{!! Form::close() !!}
This onclick function is simple submit code:
<script type="text/javascript">
function submitForm(){
$('#csv')[0].submit();
}
</script>
As you can see from the form code I have already included the csrf field. But still after this I am getting an error VerifyCsrfException.
Another thing that I have tried is to include AJAX headers:
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
</script>
But still error remains. Any suggestions?
EDIT
I changed route type to GET and added this
<button class="btn btn-warning">CSV EXPORT</button>
It works at the moment, but I'll keep the question open since this is temporary solution. I need to have POST method.

You are creating token in page by usign {{ csrf_field() }}, so you can use as
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
or add an element named _token to post data
var _token = $('input[name="_token"]').val();
data: {_token:_token,company: $('#company').val(),
Also calculate value campaignID before textbox or at the top of page

Add to rest of data the token:
data: {
"_token": "{{ csrf_token() }}"
}
Cheers!

With the jQuery serialize() method the token posted with all others form data.
data: $(this).serialize(),

Related

in Laravel I GOT AN ERROR The POST method is not supported for this route. Supported methods: GET, HEAD

I am trying to when the customer wants to upload an image or logo I want this image to display it in front of him by span element for him to make sure he uploaded the correct image to the system but when I press on upload I got POST method is not supported for this route. Supported methods: GET, HEAD. error
here is my code in card_view_blade
<div class="form-group row">
<div class="col-md-8">
<form method="post" id="upload-image-form" enctype="multipart/form-data">
#csrf
<div class="input-group" data-type="image">
<input type="file" name="file" class="form-control" id="image-input">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div>
<div class="col-md-4">
<div class="alert" id="message" style="display: none"></div>
<span id="uploaded_image"></span>
</div>
</div>
here is the js code
#section('script')
<script type="text/javascript">
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#upload-image-form').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#message').hide().html('');
$.ajax({
type:'POST',
url: `/upload-images`,
data: formData,
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success: (data) => {
console.log("success-",data);
if (data) {
this.reset();
$('#message').show().html(data.message);
$('#message').addClass(data.class_name);
$('#uploaded_image').html(data.uploaded_image);
}
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
},
error: function(data){
console.log("error-",data);
// $('#image-input-error').text(data.responseJSON.errors.file);
$('#message').show().html('Something went wrong');
$('#message').addClass('danger');
$('#uploaded_image').html('');
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
}
});
});
})
</script>
#endsection
route code
Route::post('/upload-images', 'CheckoutController#storeImage' )->name('images.store');
Nothing seems to be wrong with the code perhaps the routes are cached. Try clearing them first and see if the problem is resolved or not with the following commands:
php artisan route:clear

Any way to show div on same page using jquery? Div class has parameters. So normal Div.show() is not working as we can't pass parameter object in it

<!-- Search results tab -->
<div id="testingClass" style="display:none;">
<h3 class="theme-background">Course Results (${courseResponseList.getCourses().size()})</h3>
<br>
<c:forEach items="${courseResponseList.getCourses()}" var="course"
varStatus="loop">
<form action="/search/course/edit" method="post">
<div class="panel panel-default panel-shadow">
<div id="${course.getCourseID()}-panel-heading" class="panel-heading" data-toggle="collapse"
data-target="#${course.getCourseID() }" aria-expanded="false">
<c:set var="showAssignButton" value="false" />
<c:forEach items="${enrolledCourseList}" var="courseEnrolled"
varStatus="loop">
<c:if
test="${courseEnrolled.getCourseID() eq course.getCourseID()}">
<c:set var="showAssignButton" value="true" />
</c:if>
</c:forEach>
<tags:courseNameAndDescription courseResponse="${course}"
showAssignButtonValue="${showAssignButton}" />
</div>
<div id="${course.getCourseID() }" class="panel-body collapse">
<tags:courseMetaData courseResponse="${course}" />
</div>
</div>
</form>
</c:forEach>
</div>
Want to show above div.
jquery script.
<script>
jQuery.noConflict();
$("#searchButton").click(function (e) {
e.preventDefault();
var data = [];
$.ajax({
type: "GET",
contentType : "application/json",
url : "/search/getCourseList",
data : $("#courseSearchForm").serialize(),
contentType:"application/json; charset=utf-8",
dataType:"json",
success : function (data) {
var jsobj = JSON.parse(JSON.stringify(data));
console.log(jsobj);
//WHAT SHOULD I DO HERE ?
alert("reached");
},
error : function(e) {
alert("Failed to search....");
}
});
});
</script>
I'm getting the courselist from ajax call but I'm not able to display it on same page. Jquery.load(url) will also not work as jsp file is in WEB-INF. So we can't access it through url.
Div id="testingClass" is present in the same file.(courseSearchPage.jsp).I want to show this div when I click on search buttom.
I'm trying to best understand your problem, this code snippet works for me.
$("#searchButton").click(function(e) {
e.preventDefault();
var data = [];
$.ajax({
type: "GET",
contentType: "application/json",
url: "http://httpbin.org/get?test=chakram",
data: $("#courseSearchForm").serialize(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#testingClass').show(); //ADD THIS LINE HERE
},
error: function(e) {
alert("Failed to search....");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="searchButton">click me</button>
<div id="testingClass" style="display:none;">
<h3>your div has now been shown!</h3>
</div>

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

Laravel 5.2 : How to post and delete data Using Ajax?

I want to post some data using Ajax and I also want to delete some data using Ajax.
But the problem is while inputting the data, data posted in database. But My UI faces some problem, after saving the data, my save Button always clicked. But as I'm using Ajax, it shouldn't load or previous data should automatically vanish.
Same as for deleting also, while deleting data get deleted, but it's redirecting to another page?
How do I solve the problem?
Here is my UserController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Http\Response;
use App\User;
use App\Post;
use Illuminate\Support\Facades\Storage;
class UserController extends Controller {
public function postSignUp(Request $request) {
$this->validate($request, [
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'password' => 'required|min:4'
]);
$user = new User();
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
if ($request->ajax()) {
return response()->json();
}
}
public function delete(Request $request, $id) {
$user = User::find($id);
$user->delete($request->all());
}
}
?>
Here is my Post data View page:
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity = "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin = "anonymous">
</head>
<body>
<script src = "https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div class="container">
<h2>Register Form</h2>
<div class="row col-lg-5">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="Email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" onclick="send(event)" class="btn btn-default" >Submit</button>
</div>
</div>
<script type="text/javascript">
function send(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "{{route('signup')}}",
data: {name: $("#name").val(),
email: $("#email").val(),
password: $("#password").val(),
_token: '{!! csrf_token() !!}'
}
});
}
</script>
</body>
</html>
Here is my delete data view page:
<html>
<head>
<title> User Details </title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<div class="container">
<h3> User Details </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>User Name</td>
<td>User Email</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach($user as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->email}}</td>
<td>
Edit
<div id="deleteTheProduct">
{!! Form::open([
'method' => 'POST',
'action' => ['UserController#delete',$row->id],
'style'=>'display:inline'
]) !!}
{!! Form::hidden('id',$row->id)!!}
{!! Form::submit('Delete',['class'=>'btn btn-danger deleteUser','id' => 'btnDeleteUser', 'data-id' => $row->id]) !!}
{!!Form::close()!!}
</div>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$('.deleteUser').on('click', function (e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url(' / delete') }}'
+ '/' + dataId,
method: 'POST',
data: inputData,
success: function (data) {
console.log(data);
}
});
});
</script>
</body>
</html>
to prevent redirect problem just make .delete button as button not submit, I think this will fix your problem, if not please inform me,
to delete row please make following changes on your script code... first is yours code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
}
});
});
have some changes in above code
$('.deleteUser').on('click', function(e) {
var inputData = $('#formDeleteUser').serialize();
var dataId = $(this).attr('data-id');
// added code is
$object=$(this);
$.ajaxSetup({
headers: {
' X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ url('/delete') }}' + '/' + dataId,
method: 'POST',
data: inputData,
success : function(data){
console.log(data);
//if success status is successful and below code removes the parent row from the table
$($object).parents('tr').remove();
}
});
});
But as I'm using Ajax, it shouldn't load or previous data should automatically vanish
You will have to control that yourself, ajax is like a request to web server without reloading the page (or navigating) but the browser doesn't know what action to make after the ajax request. as you are using jQuery you can update your UI after Ajax request in success callback.
try for example returning the id of deleted object and in ajax success function.
success: function(data) {
jQuery('#'+data.id).remove();
}

How to post mutliple forms from a webpage

I want to post 2 forms using javscript, but I can't seem to figure it out. Can someone help me?
It seems like I need to submit the first form Async according to this but I don't follow their code: Submit two forms with one button
HTML
<form name="form1" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" target = "me1">
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<form name="form2" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" >
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<input name="submit" value="Submit Form" onclick="submitForms ()" type="button">
JS
function submitForms(){
document.forms["form1"].submit(); /* should be Async?*/
document.forms["form2"].submit();
}
var str1 = $( "form1" ).serialize();
var str2 = $( "form2" ).serialize();
ajaxReq(url,str1);
ajaxReq(url,str2);
function ajaxReq(url,data){
var request = $.ajax({
url: url,
type: "POST",
data: data,
dataType: "html"
});
request.done(function(html) {
console.log('SUCCESS')
});
request.fail(function( jqXHR, textStatus ) {
console.log("AJAX REQUEST FAILED" + textStatus);
});
}

Categories

Resources