I'm working on a simple web application in the laravel framework. I have blade, controller and model files and I want to insert the data into the database with the help of ajax. But, I'm not able to insert the data. Below is the code:
Thanks.
<script>
$(document).ready(function(){
$("#button").on("click", function(){
var name=$("#name").val();
var email=$("#email").val();
$.ajax({
url:'insert.php',
method:'POST',
data:{
name:name,
email:email,
},
success:function(data){
alert(data);
}
});
});
});
</script>
There are so many issue with your code:
url:'insert.php', // here you are not working in core php so url is not passed in this way
it will be like:
url:'{{ url("/insert") }}', // This 'insert' will be a route and that will be mapped to a controller function.
And if you are using:
method:'POST',
then you have to set the csrf token like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
or
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
Resolve the above issues and try again.
at least, you have to call in your script.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
Because it is POST request, your csrf_token is required.
Related
Should I create a controller file for displaying a file or picture? I used anchor tag for time meantime
you don't need a laravel code just use ajax and jquery :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"{{route('add-image-ajax')}}",
type:'POST',
data: {'_token' : '{{ csrf_token() }}', 'image': response},
success:function(data){
console.log('Crop image has been uploaded');
$('input[name = uploaded_img]').val(data.success);
$("#previewImgTag").attr('src', response);
}
})
I have a problem in ajax request in laravel 5.8
The problem
POST http://dailyshop.test/ajaxRequest 419 (unknown status)
The route
Route::get('ajaxRequest', 'FrontEndController#ajaxRequest');
Ajax Code
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#add-to-cart').click( function(e) {
e.preventDefault();
var product_id = $(this).data('id');
var url = "{{ route('addToCart') }}";
$.ajax({
type:'POST',
url:'/ajaxRequest',
data:{product_id:product_id},
success:function(data){
alert(data.success);
}
});
});
});
The function
public function ajaxRequest() {
dd('Yes! it working !');
return view('ajaxRequest');
}
This is my first attempt to use ajax to Post instead of Get. I get a 200 response as if it were working but the function in the controller is never being run.
I used this same concept in my ajax Get requests and they work fine but the Post is not working as expected and sortable('serialize') creates a Post variable so I need to use Post.
The alert in the success: function always runs as if it were successful but the controller function is never hit (I have it making a simple database change just to verify if it is running).
Ajax:
$(function() {
$('[id^="sortable_"]').sortable(
{
connectWith: '.sortable-line-item-list-5',
update : function (event, ui)
{
var items = $(this).sortable('serialize');
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
},
success: function()
{
alert('looks like it is working...');
},
});
}
});
$( '[id^="sortable_"]' ).disableSelection();
});
Route:
Route::post('api/sort_order_item', ['as' => 'api/sort_order_item', 'uses' =>'ApiController#SortOrderItem']);
Controller:
public function SortOrderItem()
{
$this_item = \pmms\Checklist_template_line_item::findOrFail(20);
$this_item->list_position = 1;
$this_item->save();
}
I think your problem is csrf_token,
Put this line in your blade page head section:
<meta name="csrf-token" content="{{ csrf_token() }}" />
then, update your ajax code like this :
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
success: function()
{
alert('looks like it is working...');
},
});
Let me know if it helps you
I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection
I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>