Assign Ajax response to php variable - php

How do I assign my ajax response to a php variable, if it is even possible?
In my Laravel controller I have this method for that purpose:
public function editProductPost(Request $request)
{
return response()->json([
'sliderValue' => $request->get('value')
]);
}
And this is my Ajax:
/**
* Ajax Post
*/
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
contentType: "application/json",
url: "{{ Route('editProductPost', $product->id) }}",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
data: JSON.stringify({
value: getSliderVal,
productId : getPrId
}),
datatype: 'json',
success: function(response) {
// get response
console.log(response.sliderValue)
}

If I understand you correctly, you want to do something like this:
public function editProductPost(Request $request)
{
// Create your JSON response
$response = response()->json([
'sliderValue' => $request->get('value')
]);
// Assign the content of the response to a variable
$responseContent = $response->content();
// Return your response
return $response;
}

Related

OctoberCMS callback for successful DB action after AJAX request

Im sending data via AJAX from my Chrome-extension to my OctoberCMS controller.
How can I recognize in my Chrome-extension that the database operation was successful?
So the goal is that I can use the done() in my AJAX call after a successful database update.
Do I have to return something from my controller?
Ajax from extension
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/saveData",
type: "POST",
dataType: "JSON",
data: { "data": data}
}).done(function((){//does nothing});
OctoberCMS Controller
function saveData(Request $request)
{
$data = post('data');
//do some actions with the data;
DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);
}
You can check for response
From server side
function saveData(Request $request)
{
$data = post('data');
//do some actions with the data;
DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);
// if all good return success
return ['success' => true];
// if something is not correct
// return ['success' => false];
}
Client side
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/saveData",
type: "POST",
dataType: "JSON",
data: { "data": data}
}).done(function((data){
if(data.success == true) {
// yes all good data is updated
}
else {
// data is not updated some error handling
}
}).fail(function() {
// data is not updated some error handling
// failed in case server is not able to answer or error
});
if any doubt please comment.

Can't check if request is ajax with $request->ajax() and Laravel 5.4

I have a problem trying to check if a request is ajax. This is my code:
Route
Route::post('cookies-alert', 'CookiesController#weUseCookies')->name('cookies.weuse');
Controller
namespace app\Http\Controllers;
use Illuminate\Http\Request;
class CookiesController extends Controller
{
public function weUseCookies(Request $request)
{
if($request->ajax()){
return response()->json(['status' => 'successful']);
}else{
return response()->json(['status' => 'error']);
}
}
}
The form (with Laravel collective, it auto create the _token)
{{ Form::open(['route' => ['cookies.weuse', ''], 'method' => 'POST', 'id' => 'cookie-form']) }}
....
<button type="submit">Ok</button>
{{ Form::close() }}
And the js
$('#cookie-form').on('submit', function(e){
e.preventDefault();
// .....
$.ajax({
url: url,
method: 'POST',
dataType: 'JSON',
data: data
}).done( function (response) {
var res = response;
if( res.status == 'successful' ){
console.log(res.status);
}else{
showError('error :(');
}
});
});
i tried with this other way
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'JSON',
success: function (data) {
console.log(data);
}
});
and using jquery 3.2.1 from https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
But it always return "error" from my controller.
I also tried to use Request::ajax() like this but it jump the if{} and go to the else{} option from my controller.
What am i doing wrong?
My code works on local but not on the server
laravel uses X-Requested-With http header to check if the incoming request is an ajax or not also you have to add #csrf field to your form :
$.ajax({
url: url,
type: 'POST',
// add _token field for csrf protection
data: {
_token : ''
},
dataType: 'JSON',
// add x-forwarded-with also add X-CSRF-TOKEN header for csrf protection
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': ..,
}
});
or you can use axios because laravel works better with it :
axios({
method: 'POST',
url: 'url',
data: {
_token: 'token',
},
responseType: 'json',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': 'token,
}
}
Request::wantsJson()
It's working with axios as well.
you need set header like bellow in app.js
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
window.Vue = require('vue');
$request->wantsJson() works well with axios on laravel 8.

Laravel and AJAX doesn't return anything

I want to return data from my database with .ajax() but it throws out an error with the entire HTML of a page. Why is it doing that?
My .ajax() call:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
route
Route::get('reports/groupsUsersGet',
array(
'as' =>'groupsUsersGet',
'uses' => 'ReportsController#groupsUsersGet'
)
);
view(form)
{{ Form::select('grup',$group,null,['class'=>'form-control','id'=>'group']) }}
controller
$term = Input::get('group_id');
$results = array();
DB::table('users')->where('group', 'LIKE', '%'.$term.'%')->get();
foreach ($queries as $query) {
$results[] = [
'id' => $query->id,
'value' => $query->nick
];
}
return Response::json($results);
Also send the csrf_token() as data.
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
_token: <?php echo csrf_token();?>,
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
It seems to me that you aren't sending CSRF token in the request, as #HikmatSijapati specified. In ajax request you can pass csrf token like this:
You could, for example, store the token in a HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Hope this helps!
Try this:
In your controller you can't define $queries variable inside your method.
ajax call
$.ajax({
url: "{{ URL('reports/groupsUsersGet') }}",
method: 'GET',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
alert(data);
},
error: function (data) {
console.log('Error:', data);
}
});
controller
$term = Input::get('group_id');
$results = array();
$queries = DB::table('users')->where('group', 'LIKE', '%'.$term.'%')->get();
foreach ($queries as $query) {
$results[] = [
'id' => $query->id,
'value' => $query->nick
];
}
return Response::json(['results' => $results], 200);
Thank you everyone for your help but the error was in my not including use Response at the top of controller. When I did that it worked.

Codeigniter: Ajax Request, global variable in controller

I setting the global variable in the __construct();
function __construct()
{
parent::__construct();
//variables
$this->galleryID = $this->uri->segment(3);
$this->productID = $this->uri->segment(4);
}
After a selection is made from a dropdown menu I make an ajax request.
$.ajax(
{
type: 'POST',
url: '/beta/checkout/getCoverSizes',
data: {
column: size
},
dataType: 'json',
success: function (json)
{
console.log(json);
}
});
And at this point, simply output the global variable
public function getCoverSizes()
{
print_r($this->productID);
}
Currently nothing is $this->productID is returning 0, and I am positive that it is correct as function index() depends on this variable and is rendering the data correctly. The ajax request does not appear to be accessing the global variable $this->productID.
$.ajax(
{
type: 'GET', // use GET here
url: '/beta/checkout/getCoverSizes',
data: {
column: size
},
dataType: 'json',
success: function (json)
{
console.log(json);
}
});
You are using $this->uri->segment(3); for galleryID and $this->uri->segment(4); for productID but the url in ajax call doesn't have these parameters you should pass these ids in ajax call in order to get like
$.ajax(
{
type: 'POST',
url: '/beta/checkout/getCoverSizes/1/2',
//url: '/beta/checkout/getCoverSizes/galleryID/productID',
data: {
column: size
},
dataType: 'json',
success: function (json)
{
console.log(json);
}
});
And in your class i assume you have define the global variables like
class checkout extends CI_Controller {
public $galleryID;
public $productID;
// your other code
}
in java-script pass the value js to globle ajax
$("#abc").on("change",function(){
var post_data = new FormData();
ajax_request("dashboard/ajax",post_data, response,null);
});
and then in JS
function ajax_request(URL, request_data, response_function, element){
$.ajax({
type: "POST",
datatype:"json",
url: BASE_URL+URL,
data: request_data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(result){
response_function(JSON.parse(result), element);
},
error: function() {
response_function(undefined, element);
}
});
}

How to do a POST json request with jQuery?

How can I recreate a request with jquery which would work exactly as this PHP request?
$client = new Zend_Http_Client($uri);
$response = $client->setMethod(Zend_Http_Client::POST)
->setRawData(trim($json), 'application/json')
->request();
Thanks.
$.ajax({
cache:false,
type: 'POST',
url: "yoururl",
data:yourJsonData,
contentType: "application/json",
success: function(data) {
//do what you what with return data
}
});
Like this
$.postJSON("/application/json".
{
ID:5 // all parameters here for the method
},
function(data)
{
//data is what comes back from your function
});

Categories