I finally got my AJAX function working and it correctly posted data to the controller. But it only worked when the data being sent was included in the form action- /UoE/buy-product/{{product_id}}. But I only want the form action to be /UoE/buy-product/, as otherwise I am essentially sending the data twice. Once here, and once in my ajax function.
Here is my view
<form class="buy-product-form" id="{{$product->id}}" action="{{url('/UoE/buy-product')}}" method="POST">
{{csrf_field()}}
<button class="pull-right btn btn-primary">BUY NOW</button>
</form>
Here is my AJAX function
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('form.buy-product-form').on('submit', (function (e) {
e.preventDefault();
var product_id = $(this).closest("form").attr("id");
$.ajax({
url: $(this).closest("form").attr('action'),
type: 'POST',
data: {'id': product_id},
dataType: 'JSON',
success: function () {
window.alert($(this).closest("form").attr('action'));
}
});
}));
});
Here is the first line of my controller (everything else here works fine)
public function buyProduct(Request $request){
$product_id = $request->id;
And here is my routes.php file
Route::post('/{university_code}/buy-product', 'UserController#buyProduct');
Managed to fix it, I changed the routes file and removed that when a button was clicked.
Related
In Laravel -Controller name is ProductController, method is showproductinmodal .
I tried this, javascript code it worked.
Web Route:
Route::get('admin/product/show/{id}', 'Admin\ProductController#showproductinmodal');
JS:
<script>
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$(".modal-body").load("{{URL::to('admin/product/show/')}}"+"/"+productid);
});
</script>
Url loaded and returned some text to modal.
But this Javascript code not worked, i want to use code below:
$(document).ready(function(){
$('.showinfo').click(function(){
var productid = $(this).data('id');
// AJAX request
$.ajax({
url: '{{route('admin.showproductinmodal')}}',
type: 'post',
data: {id: productid},
success: function(response){
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
My web route code
Route::post('admin/product/show/', 'Admin\ProductController#showproductinmodal')->name('admin.showproductinmodal');
My Controller code:
public function showproductinmodal(Request $id)
{
return "Your test id:" . $id;
}
My a tag
Any ID test
Modal works normal, pops up when I use first javascript code everything works ok data loading, but second javascript code is necessary for me. I inserted alert also in $.ajax request but it didn't work.
Might be you are missing crsf token in you case:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Set csrf token for ajax call once then call N number of ajax:
$(document).ready(function () {
$('.showinfo').click(function () {
var productid = $(this).data('id');
let url = "{!! route('admin.showproductinmodal') !!}"
// AJAX request
$.ajax({
url: url,
type: 'post',
data: {
id: productid
},
success: function (response) {
// Add response in Modal body
$('.modal-body').html(response);
}
});
});
});
And it will me more better, if you will use bootstrap model event, and use base url with javascript global variable.
I don't have the knowledge about Ajax in combination with Laravel. I'm trying to build a like system, its already set up. The problem is; when you click on the like button, the whole page refreshes. But I want it to be dynamic. To do this, I need to use Ajax and jQuery
I have tried building a jQuery function, but I don't know how to parse the {id}
Could you show me where I can learn more about this subject? Maybe a tutorial or could you please explain to me the part I'm missing.
$('.like').on('click', function(event) {
console.log("clicked the button");
$.ajax({
method: 'POST',
url: /{id}/addlike
})
});
This is the like button:
<form action="/{{$new->id}}/addlike" method="post">
#csrf
<button value="{{$new->likes}}" class='like' type="submit"><i class="fas fa-fire"></i></button>
</form>
This is the like route:
Route::post('/{id}/addlike', 'ImageController#like');```
This is the "like" controller
public function like($id)
{
$picture = ImageModel::find($id)->increment('likes');
return back();
}
Remove type='submit' It will redirect your page, just add type="button" and in .like function() ajax should be like this, always apply if and else condition in case you getting some error so it will reflect on your browser console.
$.ajax({
type: "POST",
url: Apiurl,
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
success: function (data)
{
if(data.status == 'success' )
{
//apply your condition
}
else
{
console.log('error');
}
}
});
You can pass data in your ajax functions like data: {id: yourid, name: somename}, and also you can assign laravel variable values to js like this:
var testId = '{{$yourid}}'
So in your case you can make url like testId + '/addlike', also always make id or other dynamic thing go at the end like 'addlike/' + testId.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
})
});
Hope it helps
Don't add
return back();
in your controller instead you can use
return response()->json(['success' => 'Liked']);
or anything you want to input there to pass the data in ajax. Don't put action in your post instead you can use hidden input to put your id there and call it (if you're using jquery)
$('input [name=nameofhidden]').val();
then in your ajax add success and what you want to do after updating the data.
var id = $('input[name=nameofhidden]').val();
$.ajax({
method: 'POST',
url: '/'+id+'/addlike',
success: function(ifyouhavedata){
//what you want to do
}
})
JavaScript logic you need to return false, so it'll stop redirecting. see below code.
$('.like').on('click', function(event) {
console.log("clicked the button");
var id = '{{$yourId}}'
$.ajax({
method: 'POST',
url: id + '/addlike'
});
return false;
});
Controller should be return like below
return response()->json(['success' => 'Liked'],200);
I am making a book library site using laravel. I am trying to add bookmark functionality. I have tried doing something like that on click of bookmark button, page no is being send to database and it is working. Issue is that on return from controller page is getting reload causing book to back on page no 1. Is there is any way that data sends to database without page reload??
I know a bit that ajax do this, but I am using JavaScript in my application and I tried to deploy ajax with it but no luck.
I am showing up my code. Any good suggestions would be highly appreciated.
My javascript function:
function bookmark()
{
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
count is defined up in script.
My route:
Route::post("save_bookmark/{b_id}/{p_no}",'BookmarkController#create')->name('save_bookmark');
My controller:
public function create($b_id, $p_no)
{
$b=new bookmark;
$b->u_id=Auth::user()->id;
$b->book_id=$b_id;
$b->p_no=$p_no;
$b->save();
return response()->json([
'status' => 'success']);
}
My html:
<li><a id="bookmark" onclick="bookmark()" >Bookmark</a></li>
Note: There is a navbar of which bookmark is a part. There is no form submission.
try this: use javascript to get the book id
$("#btnClick").change(function(e){
//console.log(e);
var book_id= e.target.value;
//$token = $("input[name='_token']").val();
//ajax
$.get('save_bookmark?book_id='+book_id, function(data){
//console.log(data);
})
});
//route
Route::get("/save_bookmark",'BookmarkController#create');
you need add event to function and add preventDefault
<button class="..." onclick="bookmark(event)">action</button>
in js:
function bookmark(e)
{
e.preventDefault();
book = '<?php echo $book->id ?>';
$.ajax({
type: "post",
url: "save_bookmark",
data: {b_id:book, p_no:count},
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
}
in controller you ned use it:
use Illuminate\Http\Request;
...
...
public function create(Request $request)
{
$b=new bookmark();
$b->u_id=Auth::user()->id;
$b->book_id=$request->get('b_id');
$b->p_no=$request->get('p_no');
$b->save();
return response()->json([
'status' => 'success']);
}
in route use it:
Route::post("save_bookmark/",'BookmarkController#create')->name('save_bookmark');
Well, assuming your bookmark() JavaScript function is being called on a form submit, I guess you only have to prevent the form to be submitted. So your HTML code would looks like this:
<form onsubmit="event.preventDefault(); bookmark();">
Obviously, if you're handling events in your script.js it would rather looks like this:
HTML
<form id="bookmark" method="POST">
<input type="number" hidden="hidden" name="bookmark-input" id="bookmark-input" value="{{ $book->id }}"/>
<input type="submit" value="Bookmark this page" />
</form>
JavaScript
function bookmark(book_id, count) {
$.ajax({
type: "post",
url: "save_bookmark",
data: {
b_id: book_id,
p_no: count
},
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
let form = document.getElementById('bookmark');
let count = 1;
console.log(form); //I check I got the right element
form.addEventListener('submit', function(event) {
console.log('Form is being submitted');
let book_id = document.getElementById("bookmark-input").value;
bookmark(book_id, count);
event.preventDefault();
});
Also I would recommend you to avoid as much as possible to insert PHP code inside your JavaScript code. It makes it hard to maintain, it does not make it clear to read neither... It can seems to be a good idea at first but it is not. You should always find a better alternative :)
For example you also have the data-* to pass data to an HTML tag via PHP (more about data-* attributes).
I tried to make an ajax delete functionality in Laravel.
I cant figure out why it isnt working... There is no error but nothing happens -
Thanks for any help!
My route:
Route::post('/deleteWithAjax', 'eventController#deleteWithAjax');
My delete Button:
<button value="{{$event->id}}" class="btn btn-danger btn-dell">Delete</button>
My javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('document').on('click', '.btn-dell', function() {
var id = $(this).val();
var el = $('#{{$event->id}}');
$.ajax({
type: 'post',
url: "deleteWithAjax",
data: {
'id': id
},
success:function(data){
el.remove();
}
})
})
});
My Controller Method:
public function deleteWithAjax(Request $r){
eventModel::find ( $r->id )->delete();
return response()->json();
}
The element i want to remove is a div:
<div id="{{$event->id}}">
EDIT**
I changed the event Handler
document.getElementById("btn-dell").onclick = function()
now it gets fired - but i get an error in the console and the backend is still not called at all:
POST http://wt-projekt.test/index.php/deleteWithAjax 419 (unknown status)
send # app.js:29
ajax # app.js:29
document.getElementById.onclick # home:50
I solved the problems:
I placed the token part in the document ready function
--> No error anymore, record deleted in the DB but still in the view
I added dataType: 'text' to the ajax call
--> error also deleted in the View
Nevertheless thanks for your comments!
How do I send multiple values for AJAX Laravel.
for Example:
$('#submit_').on('click', function (e) {
e.preventDefault();
var form_data = $('#create').serialize();
var form_taxonomy = 'category';
$.ajax({
headers: {
'X-CSRF-Token': $('input[name="_token"]').val()
},
type: 'post',
url: '{!! URL::route('category') !!}',
data: {formData:form_data,formTaxonomy: form_taxonomy},
success: function () {
$('#append').load('{!! URL::route('loadCat') !!}');
},
error: function (xhr, status, errorThrown) {
alert(JSON.parse(xhr.responseText).category[0]);
}
});
jQuery("#create").val('');
});
controller code:
public function create(messageRequest $request)
{
if($request->ajax()) {
$name = Input::get('formData');
$taxonomy = Input::get('formTaxonomy');
return response()->json($name, $taxonomy);
}
}
html code:
<div class="col-sm-6">
<form method="POST" action="http://localhost:8000/category" accept-charset="UTF-8"><input name="_token"
value="IzByO9fU5yeanaVCudCQpkL5bXGzUh9B4jb400iU"
type="hidden">
<div class="form-group">
<div class="form-group">
<input class="form-control text-right" id="create" name="category" type="text">
</div>
<div id="submit_"><input name="createSub" id="submit" class="btn btn-primary" value="submit" type="submit">
</div>
</div>
</form>
message request validate:
public function rules()
{
return array(
'category'=>'required|alpha|unique:taxonomies,name',
);
}
public function messages(){
return [
'category.required'=>'fill',
'category.alpha'=>'only charecter',
'category.unique'=>'dublicate'
];
}
This code not work . I used my other examples, but no one was not responsive to the problem is that I don't know only parameter data in laravel how to call the amount that would not be faced with an error and stored in the database .
You've already serialized the form, which generates the name=value&name=value query string format. It looks like you then want to add data to this query string for submission. You will need to do this somewhat manually, but it can be done like this:
$('#submit_').on('click', function (e) {
e.preventDefault();
var form_data = $('#create').serialize();
var form_taxonomy = 'category';
$.ajax({
headers: {
'X-CSRF-Token': $('input[name="_token"]').val()
},
type: 'post',
url: '{!! URL::route('category') !!}',
// manually combine your form data and your additional post data
// into one query string
data: form_data + '&' + $.param({formTaxonomy: form_taxonomy}),
success: function () {
$('#append').load('{!! URL::route('loadCat') !!}');
},
error: function (xhr, status, errorThrown) {
alert(JSON.parse(xhr.responseText).category[0]);
}
});
jQuery("#create").val('');
});
Edit
With your existing code, the issue that you're having is that your messageRequest validation says that the category field is required, but your request data does not have a category field. Because of this, your validation is failing, and will return a 422 response with a JSON object containing your validation errors.
With the updated code above, your request data now has a category field, so validation is passing, but you have some other error in your code that is generating a 500 error. You need to track this down and fix it, which may require another question.
You are using FormRequests to act as validation for that controller method. In this case, your FormRequest is: MessageRequest - which includes a validation parameter by the name of category.
When your ajax submission takes place, it is not providing the category field, and therefore failing validation.
To test, try supplying category data to the ajax data:
data: {formData:form_data,formTaxonomy: form_taxonomy, category: 'somevalue-unique-to-your-taxonomies'},
Change your data part like this :
data: {'formData':form_data,'formTaxonomy': form_taxonomy},