Laravel 5.6 ajax request, can't read the value - ajax

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);

Related

Laravel Explode Ajax Request Containing Name and Numbers

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

Redirecting to different view after an AJAX call Laravel

I am trying to activate my user by doing an AJAX call. I have this jQuery code for that:
$(document).ready(function(){
$(document).one('click','.continue-button',function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data('id');
$.ajax({
url: '/activate',
type: 'POST',
data: {id : id},
success: function(res){
}
});
});
});
It takes the data-id attribute of my button, which is the user's id and sends an AJAX call. This is how my route looks like:
Route::post('/activate','ActiveController#activate');
My function:
public function activate(Request $request)
{
$id = $request->input('id');
User::where('id',$id)->update([
'active' => '1'
]);
return redirect('/loadDashboard');
}
It activates the user and then redirects to '/loadDashboard' route. This is how the route looks like:
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('/loadDashboard','ActiveController#loadDashboard');
});
And finally my loadDashboard function:
public function loadDashboard()
{
return view('dashboard')->with('title','Dashboard');
}
I want to redirect the user to my dashboard view in aforementioned function, but it seems to return the view to my AJAX call. I can see the view in Inspect->Network. How can I fix this problem?
Instead of this
return redirect('/loadDashboard');
put this
return response()->json(['url'=>url('/loadDashboard')]);
and in your ajax success function put this:
success: function(res){
window.location=res.url;
}

I can not return Data in ajax

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

How to get a value from ajax call in laravel

I want to get a value from the ajax call in controller function. How can i do it?
My code is here:
<i class="fa fa-pencil-square-o"></i>
My script:
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
My route:
Route::post('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
my controller function:
public function amount_to_pay($id)
{
echo $id;
}
easly return the value:
public function amount_to_pay($id)
{
return $id;
}
Use
var url = '{{ route('amount_popup', ['id' => #id]) }}';
url = url.replace('#id', id);
instead of
'amount_popup/'+ id
You are trying to get the value from a GET request, but you are sending the form as a POST request.
You should change your script code to:
<script>
function amount_pay(id)
{
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
THEN CHANGE YOUR ROUTE TO:
Route::get('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
OR IF YOU WANT TO USE POST... DO THIS...
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup',
data: "id=" + id + "&_token={{ csrf_token() }}", //laravel checks for the CSRF token in post requests
success: function (data) {
alert(1);
}
});
}
</script>
THEN YOUR ROUTE:
Route::post('/amount_popup', 'AdminController\AmountController#amount_to_pay');
THEN YOUR CONTROLLER:
public function amount_to_pay(Request $request)
{
return $request->input('id');
}
For more info:
Laravel 5 Routing

Passing an array to controller via ajax

So I am using AJAX to send an array to a controller
AJAX
$('#concept').click(function(){
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data: course,
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
$.each(result, function(a, b){
htmlStr += b.qText + '<br />';
});
alert("YEAH YOU WAS SUCCESSFUL");
$('#testing1').append(htmlStr);
} // End of success function of ajax form
}); // End of ajax call
course is an javascript array with two strings.
Controller
function getValues(){
$playlist = $this->input->post('course');
$this->load->model('get_db');
$data = $this->get_db->getAll($playlist);//$var inside ()
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
return $data;
}
Model
class Get_db extends CI_Model{
function getAll($pList){
$query=$this->db->query("SELECT * FROM questions WHERE playlistID= '$pList[0]' OR playlistID='$pList[1]'");
return $query->result();
}
}
I have done hardcoding and can confirm that the controller, and model functions work as they should. The problem lies with the 'data' parameter in the ajax I think. I just dont believe the data is being passed to the controller in the correct way. I have endlessly search other questions, and I know there are questions similar to it, but I havent found a solution in this case.
Thank you in advance for any information you can provide :)
You have to echo the JSON encoded data in the Controller instead of returning it. In the Ajax callback, you must then JSON.parse() the result before the $.each(..) call.
Controller
function getValues(){
$playlist = $this->input->post('course');
$this->load->model('get_db');
$data = $this->get_db->getAll($playlist);//$var inside ()
echo json_encode($data);
// $this->output->set_content_type('application/json');
// $this->output->set_output(json_encode($data));
// return $data;
}
Ajax-Call
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data: course,
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
var jsonData = JSON.parse(result);
$.each(jsonData, function(a, b){
htmlStr += b.qText + '<br />';
});
alert("YEAH YOU WAS SUCCESSFUL");
$('#testing1').append(htmlStr);
}

Resources