I can not get the response from the controller with Ajax,what should I do?:
$("document").ready(function(){
$("#send").click(function(e){
e.preventDefault();
var question = $("input[name=question]").val();
$.ajax({
type: "POST",
url : "/Admin/question/store?token={{$t}}",
data : {'question':question},
success : function(data){
alert(data);
console.log(data);
}
});
});
});
and in the controller I just want to return a string for testing:
public function store(Request $request)
{
return "success";
}
For you to get the response in AJAX you must print the data, is it being print after the return? if not, try :
public function store(Request $request)
{
echo "success";
}
I solved it,
First problem was URL,I changed it to:
{!! route('store') !!}
And did not know to write my route in api!!!! instead of web
Related
I'm using laravel 8.4 .
My route :
Route::post('test',[\App\Http\Controllers\DataController::class, 'store'])->name('pos-test');
My Controller :
public function store(Request $request)
{
// DB::table('data')->insert('product_code',$request->id);
$badge = explode(' ', $request);
$employee_id = $badge[0];
\DB::table('data')->insert(['product_code'=> $employee_id]);
return response()->json(['success'=>'Product saved successfully.']);
}
Ajax code :
function handleBarcode(scanned_barcode) {
//handle your code here....
console.log(scanned_barcode);
let _token = $('meta[name="csrf-token"]').attr('content');
event.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('pos-test') }}",
type: "POST", // Can change this to get if required
data: {
code : scanned_barcode,
_token: _token
},
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
console.log(jqXHR);
}
});
};
The request is like this "555444 Razif Raziq" , i would like to explode it so I may insert only "555444" into table but in table column product_code is 'POST' .
The question is how to fix it? thank you
you must explode your correct data in request object not request object itself.
$badge = explode(' ', $request->code);
If the 'code' value is sent correctly, just use this
$request->code
public function store(Request $request)
{
\DB::table('data')->insert(['product_code'=> $request->code]);
return response()->json(['success'=>'Product saved successfully.']);
}
i'm trying to redirect to Controller with data and use that data in controller ( i'm using laravel)
/* html */
<a #click="Submit()" href="/buy" class="btn btn-block btn-lg btn-primary btn-checkout-pay">Buy</a>
/*js codes*/
Submit : function(){
axios.post('/buy',{
ProductId : this.id,
//ProductId : "1";//
ProductAmount : this.temporaryamount
//ProductAmount : "12000";//
})
.then(function (response) {
window.location = "/buy";
console.log(response);
})
.catch(function (error) {
console.log(error);
})
}
and the /buy is redirected to ShoppingController#create
/* web.php */
Route::get('/buy','ShoppingController#create');
Route::post('/buy','ShoppingController#create');
/* ShoppingController#create */
public function create(Request $request)
{
dd($request['ProductId']);
}
the problem is $request['ProductId']; is null
that means axois request is redirected without the data
P.S : i don't wan't to return the data i wanna just use the data in controller
Basically, you cannot used together those two create functions with different route method and at the same time you want to get the product id. Your post request will work on that situation but the get request will not. that's why dd($request['ProductId']) is null. You cannot use request as a parameter whenever you use a get request. $request as a parameter is for post request only.
for further explanation please read laravel docs source
so to solve your problem, you may remove this line
window.location = "/buy";
and show your post data in the controller by this
public function create(Request $request) {
dd($request->all())
}
if i understand correctly your problem is that you don't see the return of "dd".
It's normal your console.log is after the window! and no dd with axios! you have to return to see the answer!
Controller
public function create(Request $request)
{
return $request['ProductId'];
}
.vue
/*js codes*/
Submit : function(){
axios.post('/buy',{
ProductId : this.id,
//ProductId : "1";//
ProductAmount : this.temporaryamount
//ProductAmount : "12000";//
})
.then(function (response) {
console.log(response);
//Remove window.location, or if you dont remove you dont see console.log!
//window.location = "/buy";
})
.catch(function (error) {
console.log(error);
})
}
and on your route remove get.
/* web.php */
Route::post('/buy','ShoppingController#create');
I am using an ajax request to show some information, on my local development version it works perfectly, but on the production server (Ubuntu 16.04 LEMP) it fails in validation, because there is no data in the request.
Checks
The url is correctly showing (e.g. example.com/employeeInfo?employeeId=1)
Ajax itself is working: when I hard-code the controller's response everything is fine.
I cannot figure out why this happens in production, but not on the local version... Huge thanks for any clues!
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
var employeeId = $(this).data('id');
// Get data
$.ajax({
type: "GET",
url: "employeeInfo",
data: {employeeId:employeeId},
success: function(data){
var obj=$.parseJSON(data);
$('#team-info-title').html(obj.output_name);
$('#team-info-subtitle').html(obj.output_role);
$('#resume').html(obj.output_resume);
$('#linkedin').html(obj.output_linkedin);
$("#team-info-background").show();
$("#team-info").show();
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#getInfo');
Controller
public function getInfo(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'employeeId' => 'required|integer',
]);
$employee = Employee::find($request->employeeId);
$output_linkedin = '<i class="fab fa-linkedin"></i>';
$data = array("output_resume"=>$employee->resume,"output_linkedin"=>$output_linkedin, "output_name"=>$employee->name, "output_role"=>$employee->role);
echo json_encode($data);
}
}
If you want to pass a get data employeeId you have to pass a slug through your route either you should pass the data by POST method.
Route::get('/employeeInfo/{slug}', 'EmployeeController#getInfo');
And Get the slug on your function on controller .
public function getInfo($employeeId)
I can't read the values send with ajax request, i don't know what im missing.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#send").click(function(e){
e.preventDefault();
var id = 5;
$.ajax({
type:'POST',
url:'/device/',
data:{id:id},
success:function(data){
console.log('Yes' + data);
}
});
});
in the controller device i just dump the input from the ajax call
$data = $request->all();
dd($data);
I can't see the value send via ajax in the console, i only see Yes but not the data.
What im missing ?
use the following line in your controller;
return $data; instead of dd($data);
Just Replace the + with , like below
console.log('Yes' , data);
try this in controller
public function store(Request $request) {
return Response::json($request->all(), 200);
}
dont forget to include
"use Response;
use Illuminate\Http\Request;"
Use This:
$("#send").click(function(e){
e.preventDefault();
var id = 5:
$.ajax({
type:'POST',
url:'{{url('/device')}}',
data:{
'ajax': 1,'id':id,'_token': {{csrf_token}}
},
success:function(data){
console.log('Yes'+data.id);
}
});
});
In the controller use:
public function name()
{
if(Input::get('ajax') == 1)
{
print_r('Ajax is working');die;
}
}
Also make sure, in the route you have post or any and not get for this route.
try this one.
in controller:
return $data;
And simply replace + with, like this:
console.log('Yes' , data);
I got this error from Ajax call ! it's get action from checkbox then send data by Ajax to controller method,
jquery.min.js:4 POST http://localhost:8000/listhotelregisration 500 (Internal Server Error)
Here's the code html part:
<div style="display:block">
<div>My hotel Lists</div>
#foreach($myLists as $key => $val)
{{ $val['name'] }
{!! Form::checkbox($val['name'], $val['id'].','.$value['id']) !!} <br>
#endforeach
</div>
Ajax part:
$(function() {
$("input[type='checkbox']").change(function() {
var smi = $(this).val();
// alert(smi);
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {'checko':smi},
success: function(data){
//alert(data);
}
});
});
Route part:
Route::post('listhotelregisration', 'ListhotelController#create');
Controller part:
public function create(Request $request)
{
$listhotel = new listhotel;
$data = $request->all();
$dataPrim = explode(",", $data);
$listhotel->id_list= $dataPrim[0];
$listhotel->id_hotel= $dataPrim[1];
$listhotel->save();
$response = "ok";
return response ()->json ($response);
}
Ajax in Laravel 5
This is mainly due to The VerifyCSRFToken middleware that laravel provide us out-of-the-box. It responds an Internal Server Error (500) when token mismatch occur on our requests.
We need to send our AJAX request with token sent to our browser.
The CSRF token is mostly stored in the meta tag, you can put it any where though
$.ajaxSetup
Set default values for future Ajax requests
Solution
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
Hope this helps.
error 500 will mean this is a server error.
To know exactly what went wrong you need to check the response the server is returning.
In any case i would already adjust your following pieces:
Javascript:
$(function() {
$("input[type='checkbox']").change(function() {
var id_list = $(this).attr('id_list');
var id_hotel = $(this).attr('id_hotel');
$.ajax({
url: 'listhotelregisration',
type: "post",
data: {
'id_list': id_list,
'id_hotel':id_hotel
}
}
});
});
Controller:
public function create(Request $request)
{
$data = $request->only(['id_list', 'id_hotel']);
$listhotel = listhotel::firstOrCreate($data)
return response ()->json ("OK");
}