I am trying to generate the route for an Ajax call in my file.js. I have installed FOSJsRoutingBundle and followed the instruction. I exposed my route for the request but the Routing.generate() method gives the error The route 'ajax' does not exist. I tested the route with a button and it works.
The Javascript file
$('#add_assistant_next').click(function () {
var route = Routing.generate('ajax');
var that = $(this);
var i = $.ajax({
url: route,
type: "POST",
dataType: "json",
data: {"ajax-user": "test user string"},
async: true,
success: function (data) {
$('div#ajax-results').html(data.output);
}
});
return false;
});
The controller route
/**
* #Route(name="ajax", options={"expose" = true},
* methods={"GET", "POST"},
* path="/ajax")
*
*
*
*/
public function ajaxAction(Request $request)
{
dump('route called');
die();
if ($request->request->get('ajax-user')) {
dump('request recieved');
die();
}
}
You need to dump your routes every time you add new route
https://symfony.com/doc/master/bundles/FOSJsRoutingBundle/usage.html
Related
I want add product to the cart through ajax. only logged in user can add product to the the user. if user is not logged in redirect him to the log in page
Here are my ajax request in blade template
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function addedToCart(){
var product = $("#productId").val();;
var val = $("#countItem").val();
var unit = parseInt(val);
$.ajax({
type: "POST",
url: "/addtocart",
data: {product: product, unit: unit},
dataType: "json",
success: function (res){
alertMsg.fire({
title: 'Product added to Cart'
})
}
});
}
`
Here the controller code
function addToCart(Request $req){
if($req->session()->has('user')){
$cart = new Cart;
$cart->user_id = $req->session()->get('user')['id'];
$cart->product_id = $req->product;
$cart->unit = $req->unit;
$cart->save();
return response($cart, 201);
}
else{
return redirect('/login');
}
}
It can not go the login route still remain in the same page
Ajax request expects JSON Array Literals, such are JSON formatted array/objects and plain strings, in response. Meaning, you can't make redirect object return in PHP.
You can
// in controller
if (!$req->session()->has('user')) {
return response()->json([
'error' => "Forbidden"
], 403);
}
// save the cart and return success object
Then
// in JS
$.ajax({
type: "POST",
url: "/addtocart",
data: {product: product, unit: unit},
dataType: "json",
success: function (res){
alertMsg.fire({
title: 'Product added to Cart'
})
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
window.location = 'path_for_guests'// this path should be returned from backend for greater security
}
});
Also, be aware of not saved objects. For example, if $cart is not successfully saved you shouldn't return success message. Which is your code doing right now. To follow Object Calisthenics appropriate code (one else it too much), you can use switch and in suitable cases match for various exceptions and expectations like
user session doesn't exist 403
object not created 500
cart created 201
etc
in JSON response you can not use redirect at server side.
either you can play with status here like if the user is logged in, then perform your action, otherwise return a response with status: false.
I have modified your code link below and I have added in comments on what I have changed.
Your JS code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function addedToCart(){
var product = $("#productId").val();;
var val = $("#countItem").val();
var unit = parseInt(val);
$.ajax({
type: "POST",
url: "/addtocart",
data: {product: product, unit: unit},
dataType: "json",
success: function (response){
if (response.status) { // if it is true
alertMsg.fire({
title: 'Product added to Cart',
});
} else {
// if it is false, redirect
window.location.href = response.redirect_uri;
}
},
});
}
Your controller function:
function addToCart(Request $request){
if($req->session()->has('user')){
$cart = new Cart;
$cart->user_id = $request->session()->get('user')['id'];
$cart->product_id = $request->product;
$cart->unit = $request->unit;
$cart->save();
return response($cart, 201);
}
else{
// you can return with status flag, and using the redirect_uri your can redirect at your desire page.
return response()->json(array(
'status' => false,
'redirect_uri' => route('login'),
), 401);
}
}
Not sure, about the false status you will get in the AJAX success(), if you will not get then you will have to add the error function after the success(). as we are passing header status in the response.
error: function (error) {
// do console log to check what you get
}
I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.
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);
}
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!
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