how to send data from ajax get method to controller in laravel? - ajax

Proceed to booking
on clicking the button i call the ajax function code below
$("#add_cart").click(function()
{$.ajax({
url: 'roombooking',
type: "get",
data: {id:data},
success: function(response){ // What to do if we succeed
if(data == "success")
alert(response);
}
});
});
Route
Route::post('roombooking','pagescontroller#roombooking');
Controller
public function roombooking($id,request $req)
{
$input = $req->all();
return view ('pages.roombooking')->with('id',$id);
}

Route::post('roombooking','pagescontroller#roombooking');
change to
Route::get('roombooking','pagescontroller#roombooking');

Related

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

Cannot insert ajax data into database codeigniter

I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}

laravel ajax function doesn't return a value

Hello I'm working on laravel and trying to make a ajax action
function jsfunctionrr(value){
var value_parts = value.split("+");
$.ajax({
type: 'POST',
url: '/getpoinsts',
data: {
'_token': $('input[name=_token]').val(),
'name': value_parts[1]
},
success: function (data) {
$('#pointsValue').append(total_points);
}
});
and the controller function
public function getpoinsts(Request $request)
{
$user_points_parts = DB::table('clients_points')->where('user_id', $request->name)->get;
$total_points = 0;
foreach ($user_points_parts as $points_part) {
$total_points += $points_part->points;
}
return response()->json($total_points);
}
and the route
Route::post('/getpoinsts', 'LoyalityController#getpoinsts');
but I get no value in back any one know why ??
There are a few issue in your code that I've noticed:
->get; should be get();
There might be an issue with trying to convert a number to json.
In your ajax method you're referencing total_points but it isn't defined anywhere.
Try changing your controller method to:
public function getpoinsts(Request $request)
{
$total_points = DB::table('clients_points')->where('user_id', $request->name)->sum('points');
return response()->json(compact('total_points'));
}
and your ajax method to:
$.ajax({
type: 'POST',
url: '/getpoinsts',
data: {
'_token': $('input[name=_token]').val(),
'name': value_parts[1]
},
dataType: 'json',
success: function (data) {
$('#pointsValue').append(data.total_points);
}
});
Hope this helps!

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