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},
Related
I've set up two buttons which when clicked are just sending their values to my controller, then I am trying to send back AJAX HTML to show the users profile on the main page. I can't get the input id to make it to the controller no matter what I try.
Here's the HTML:
<ul class="signup-li">
#foreach($participants as $participant)
<button type="submit" name="id" value="{{$participant->id}}">
{{$participant->phone}}
</button>
#endforeach
</ul>
Here is my JS:
$(document).ready(function(){
$("button").click(function() {
var id = $(this).val();
console.log(id);
$.ajax({
type:'POST',
url:'/get-profile/',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: { "id" : id },
success: function(data){
console.log('hi');
},
error: function(xhr,textStatus,thrownError) {
alert(xhr + "\n" + textStatus + "\n" + thrownError);
}
});
});
});
Here is my controller function:
public function getProfile(Request $request)
{
$id = $request->input('id');
Log::info($id);
$participant = Participant::where('id','=',$id)->first();
$returnHTML = view('ajax.user-profile')->with('participant', $participant)->renderSections()['content'];
return response()->json(array('success' => true, 'html'=>$returnHTML));
}
What am I doing wrong? I try to log the request and nothing comes through. I have CSRF disabled for this route. The issue is that the participant is not found because the ID is not getting to the controller. Why isnt it making it?
You may add dataType: 'json', to your $.ajax({...}) call
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.
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).
SOLUTION IN LAST COMMENT OF ANSWER
I have this function here
function delTag(e, name){
var tag_id = $(e).attr('rel');
$.ajax({
type: "DELETE",
url: '/admin/tags/'+ tag_id+'' ,
success: function(data){
$('#tags_tr'+tag_id).remove();
toastr.error('Tag '+name+' has been deleted');
console.log("dsa");
},
error: function(data){
console.log('Error:');
}
});
}
I call it like this:
#foreach($tags as $tag)
<button onclick='delTag(this, "{{$tag->name}}")' rel={{$tag->id}} type="button" data-dismiss="modal" class="btn btn-danger">Yes</button>
#endforeach
And i get this:
My record is deleted from the database correctly, but, ajax throws error. Why is this happaneing?
Here is my whole route if it helps...
Route::get('admin/', 'AdminController#getAdminIndex')->name('admin.index');
Route::delete('admin/users/{id}', 'Auth\\RegisterController#destroy')->name('admin.users.destroy');
Route::put('admin/users/{id}', 'Auth\\RegisterController#update')->name('admin.users.update');
Route::resource('/admin/posts', 'PostController');
Route::resource('/admin/roles', 'RoleController');
Route::delete('/admin/comments/{id}/{user_id}', 'CommentsController#destroy')->name('comments.destroy');
Route::resource('/admin/comments', 'CommentsController', [
'except' => ['store', 'destroy']
]);
Route::get('/administrator', 'AdminController#getAdmin')->name('admin');
Route::put('/admin/comments/approve/{id}', 'CommentsController#updateApprove')->name('admin.comments.approve');
Route::put('/admin/tags/associate/{tagName}', 'TagController#updateAssociation')->name('admin.tags.associate');
Route::put('/admin/categories/associate/{categoryName}', 'CategoryController#updateAssociation')->name('admin.categories.associate');
Route::resource('/admin/categories', 'CategoryController');
Route::resource('/admin/tags', 'TagController');
Route::get('/admin/pages/tables/{user_id}', 'AdminController#getTables')->name('admin.pages.tables');
Route::get('/admin/pages', 'AdminController#getIndex')->name('admin.pages.index');
With the ajax call you need also to provide csrf_token.
You can keep it on the page in the hidden input field, like this for example:
<input id="csrf" type="hidden" name="_token" value="{{ csrf_token() }}">
And then add it to your ajax call with key "_token". So your delTag function will become something like this:
function delTag(e, name){
var tag_id = $(e).attr('rel');
var csrfToken = $("#csrf").val(); // here you're obtaining token from the page
$.ajax({
type: "DELETE",
url: '/admin/tags/'+ tag_id+'' ,
data: {
"_token": csrfToken //Here you're passing the token
},
success: function(data){
$('#tags_tr'+tag_id).remove();
toastr.error('Tag '+name+' has been deleted');
console.log("dsa");
},
error: function(data){
console.log('Error:');
}
});
}
Excuse me, I want get employ value to ajax post,
then laravel controller get data(json) insert to database,
but jquery.map "bruce" is error, How can I do? , Please Help me thanks!
this is json
format
{"data":{"bruce":"[{"employ":"bruce"},{"employ":"peter"}]","_token":"UiKUMMZRqTgYv5"}}
HTML
<input type="button" class="btn ahr-button_2 employ" value="bruce">
<input type="button" class="btn ahr-button_2 employ" value="peter">
<input type="button" class="btn ahr-button_2 employ" value="abcd">
<input type="button" class="btn ahr-button_2 employ" value="efgh">
完了
Javascript
$('.employ').click(function(){
$(this).toggleClass('active');
});
$(".finish_sumbit").click(function(e){
e.preventDefault();
var data = $('.employ.active').map(function() {
return {
'employ': this.value
}
}).get();
$.ajax({
type: "POST",
url: "business_a",
async:false,
dataType: "json",
data: {bruce:data,_token:token},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
laravel route
Route::post('/business_a', 'BusinessController#business_a');
laravel controller
public function business_a(Request $request)
{
$employ = new Employ;
$b = $employ::create([
'employ' => $request->bruce,
]);
}
You need to first access the input or use the get() method on $request:
public function business_a(Request $request)
{
$employ = new Employ;
$b = $employ::create([
'employ' => $request->get('employ')
]);
}