JQuery ajax post data(json) to laravel, then laravel create data - php

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')
]);
}

Related

AJAX data is not submitting to Laravel controller - Laravel 6

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

To show Ajax call value on same controller while using front controller

I wanted to send ajax data to controller page and display ajax data on template file in prestashop 1.6 .
I am using this method but not able to get any results -
tpl file :
<input type="button" class="btn btn-primary" id="test" onclick = "testing()" value="test" />
function testing() {
url = '{$link->getModuleLink("hotelapi", "filter")|escape:"html"}';
$.ajax({
url: url,
type : 'GET',
cache : false,
data : {
ajax: 1,
action: 'fetchTPL',
},
success: function(html){
alert("SUCCESS:");
},
error: function() {
alert("ERROR:");
}
});
}
Front Controller file - File name is - filter.php
<?php
/*require (dirname(__FILE__) . '/../../../../config/config.inc.php');
require (dirname(__FILE__) . '/../../../../init.php');*/
class hotelapiFilterModuleFrontController extends ModuleFrontController
{
public function displayAjaxFetchTPL()
{
echo 'hello';
//after processing all data just assign it to smarty of content
/*$this->context->smarty->assign(array(
'youContentData' => $_POST['room'])
);
// to fetch a tpl file use fetch method and use die function to return the response to ajax
die($this->context->smarty->fetch('a1.tpl'));*/
}
}
My ajax url is executing successfully but I am not able to print anything written inside displayAjaxFetchTPL action.
Please anyone help me with this problem.
Thanks and regards,
Ridhi Bhutani
php:
public function displayAjaxFetchTPL()
{
$data = ['mYtxt' => 'hello'];
die(Tools::jsonEncode($data));
}
jquery:
success: function (html) {
alert(html.mYtxt);
},
Instead of using the "onclick" event on your button, why not use a JQuery event lsitener?
Your HTML would be something like this:
<input type="button" class="btn btn-primary" id="test" value="test" />
And your JS like this:
$("#test").on("click", function () {
url = '{$link->getModuleLink("hotelapi", "filter")|escape:"html"}';
$.ajax({
url: url,
type: 'GET',
cache: false,
data: {
ajax: 1,
action: 'fetchTPL',
},
success: function (html) {
alert("SUCCESS:"+html);
},
error: function () {
alert("ERROR:");
}
});
});

easy autocomplete is not working on class of input box

I have one input box and I have applied easy autocomplete, with the help of a class and I have added input button on clicking on that button it adds one more input box with same and I can add as many as input box but easy autocomplete is not working on all the added input box, they have the same class.
var options = {
url: function (phrase) {
return "all_social_media.php";
},
getValue: function (element) {
return element.name;
conole.log(element.name);
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json",
}
},
preparePostData: function (data) {
data.phrase = $(".social_media").val();
return data;
console.log(data);
},
requestDelay: 400,
list: {
onSelectItemEvent: function() {
}
}
};
$(".social_media").easyAutocomplete(options);
found the solution, I have to rewrite the code of easy autocomplete code at the time of dynamically generated text box
//create new socials and expenses fields
$("#add_socials").click(function(){
var html_data = $('<div class="row" style="margin-top:10px;"><div class="col-md-5"><input type="text" class="form-control social_media" placeholder="Enter Social Media" name="social_media"></div><div class="col-md-5"><input type="text" class="form-control social_media_expenses" name="social_media_expenses" placeholder="Enter Expenses"></div><div class="col-md-2"><button type="button" class="btn btn-icon btn-danger mr-1" onclick="delete_socials(this)"><i class="fa fa-times"></i></button></div></div>');
$(".add_social_data").append(html_data);
// easy auto complete is not working on dynamic generate text box, need to do this again
var options = {
url: function (phrase) {
return "all_social_media.php";
},
getValue: function (element) {
return element.name;
conole.log(element.name);
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json",
}
},
preparePostData: function (data) {
data.phrase = $(".social_media").val();
return data;
console.log(data);
},
requestDelay: 400,
list: {
onSelectItemEvent: function() {
// get_order_id = $("#order_line_entry").getSelectedItemData().order_id;
// console.log(get_order_id);
}
}
};
$(".social_media").easyAutocomplete(options);
html_data.find('.social_media').easyAutocomplete(options);
});
for me, it is working fine.

MethodNotAllowed on deleting an item with AJAX and Laravel

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:');
}
});
}

How to send multiple parameter AJAX in Laravel 5.2

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},

Categories