laravel ajax action url with parameters - php

I have a problem with an ajax call. The url that i need to get the data is:
localhost/public/getCode?course_id=1&task_id=1
My ajax call is:
function getCode() {
$.ajax({
type: "GET",
dataType: 'json',
url: "{{action('CodeEditorController#getCode',['course_id'=>$course,'task_id'=>$maintask])}}",
success: function (data) {
console.log(data);
}
});
}
But the data returned is empty.
Edit:
getCode function:
public function getCode(Request $request)
{
$code=Code::where('user_id',$user->id)->where('main_task_id',$request->input('task_id'))->first()->code;
$response = [
'data' => $code
];
return response()->json($response, 200);
}
What is the issue with my ajax code?
Thanks!

One way to do that is to use data for options:
data: {
'course_id': {{ $course }},
'task_id': {{ $maintask }}
},
To get values in controller you can just use request('course_id') and request('task_id')
Also it's a really bad idea to use Blade/PHP to build JS. You should use hidden inputs or something to pass data to JS.

Related

OpenCart 3 - AJAX Query is not working (Invalid token session)

I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:
<script>
$(".remove-request-btn").on('click', function () {
let request_id = $(this).data('request-id');
let confirm_result = confirm('Are you sure you want to delete this request?');
if (confirm_result) {
$.ajax({
url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
method: 'post',
dataType: 'json',
data: {request_id: 11},
success: function(data) {
if (data.status === 'ok') {
location.reload();
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
My method:
public function removeRequest()
{
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode(
[
'status' => 'ok'
]
));
}
I expect json in the response but get following:
I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}'
But it doesn't help. Can you help me please what I'm doing wrong? Thank you!
1-please add bellow code into controller method
$data['token'] = $this->session->data['user_token'];
2- use javascript into .twig file - not external js file.
In OC3 is used user_token instead token
so you must use this url:
url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',
And do not forget declare user_token in the corresponding controller file:
$data['user_token'] = $this->session->data['user_token'];

How to use data serialized from ajax call

I have a problem.
I have an ajax call that have two data to send, one is a form serialized the other is a other variable, i don't know how to use the variables into the first data of ajax call ( the form serialized ) into PHP, how can i do this?
JS:
$.ajax
({
url: "/update",
type: "post",
data:
{
form: $("#formTeamLeaderProduzione").serialize(),
type: "TeamLeaderProduzione"
},
success: function (data)
{
alert(JSON.stringify(data))
},
error: function (msg)
{
alert(JSON.stringify(msg));
}
});
PHP:
Route::post('/update', function (\Illuminate\Http\Request $request)
{
$value = \Illuminate\Support\Facades\Input::get('form');
return response()->json($request->form->inputModificaNomeTeamLeaderProduzione1,200);
});
This is my anwser
Route::post('/update', function (\Illuminate\Http\Request $request)
{
parse_str($request->input('form'), $form);
return response()->json($form['inputModificaNomeTeamLeaderProduzione1'],200);
});

send data from jQuery to laravel controller

i'm using laravel and i want to receive data from jQuery to my controller to insert it to the database , i tried many methodes but without success
this is my script :
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
url:'/test',
type: 'POST',
dataType: 'JSON',
data: {
"name": "Name",
"color": "red",
},
});
and the controller :
public function test()
{
if(Request::ajax()) {
$data = Input::all();
}
dd(json_decode($data));
}
and finally the Route :
Route::post('/test',[
'uses' => 'TagsController#test'
]);
it seems ok for me but the result :( :
Maybe the problem is in your controller, because you don't tell the server, which table do you want to use to store your data
or maybe because of your url.. jquery does not understand what is {{}}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/test',
method: 'post',
data: $('#form-id').serialize(), // prefer use serialize method
success:function(data){
console.log(data);
}
});
Controller:
use Illuminate\Http\Request;
public function test(Request $request)
{
if($request::ajax()) {
$data = $request->color;
}
dd(json_decode($data));
}
I am using serialize because It's so powerful, I don't need to input one by one the field name
I don't know if your controller is used for only retrieve the data from client or you want to use ajax to store your data in database.. so, I am using $request->color to make sure that the data is retrieved from the client side
Add this meta tag in main blade page
<meta name="csrf-token" content="{{ csrf_token() }}">
And instead of old scholl jquery ajax.. just use Axios. it exist inside app.js. simple and very easy. it already detect the csrd-token meta tag. so no need to do in the form or header
change this
$.ajax({
url: '{{route("test")}}',
method: 'post',
data : {
"name": "Name",
"color": "red",
},
success:function(data){
console.log(data);
}
});
to this
axios.post('{{route("test")}}', {
"name": "Name",
"color": "red"
})
.then(function(response) {
console.log(response);
});
Your Route must be like this.
Route::post('/test',[
'uses' => 'TagsController#test'
])->name('test');
Your controller seems fine..
public function test(Request $request)
{
if($request->wantsJson()) {
$data = $request::all();
return $data;
}
}

How to correctly implement a simple search functionality with ajax in laravel?

I am trying to code a simple search functionality for learning purposes, but I am failing to make it work.
What I want for now is simply to pass some data(to a controller function) in a blade view with ajax and then display this data in another view via the same controller function.
What I currently have is this :
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$data = $request->data;
return view('search-results')->with('data',$data);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1>{{$data}}</h1>
#endsection
And finally the ajax :
var data = "success";
$.ajax({
url: 'search-results',
type: "get",
data: {data : data},
success: function(response){
if(data == "success")
console.log(response);
}
});
Can someone help me make this work? I am not sure what am I doing wrong...
You should return JsonResponse object to easy use data in JavaScript
Action:
public function search(Request $request){
$data = $request->data;
return new JsonResponse(compact('data'));
}
JavaScript:
$.ajax({
url: "/search",
type: "get",
data: {data : data},
success: function(response){
console.log(response);
}
});
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$result = [];
$result['data'] = $request->data;
return response()->json($result);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1 class="header"></h1>
#endsection
Ajax call :
var data = "success";
$.ajax({
url: "{{ route('search') }}",
type: "get",
data: {'data' : data},
success: function(response){
if(response.data == "success")
console.log(response.data);
$('.header').text(response.data);
}
});
Hope it's help you!!!
An AJAX call is asynchronous therefore you can make a call and return the results in a separate form. If you want to show your results in a separate form, i advise that you submit the form and then return the view with your data return view('search-results')->with('data',$data); or if you stick to an an ajax call, you return a response which will be sent to the form where the data was submitted from return response()->json(["data" => $data]);

Get data from controller and then print it via ajax

I have print action, witch get all my records from db
public function printAction()
{
$users = $this->getDoctrine()->getRepository('ModelBundle:Users')->findAll();
$resp = new JsonResponse($users, 200);
return $resp;
}
I want use this data and print via ajax in div element, but i cant understand, how i can do it. Maybe anybody know. Please, help me.
Do you have a serializer in your user entity? Because you are getting all users as entities. I suggest you to do something like this:
When you click a button or any element, call your route like this:
//change this element to your button
$('a.press-me').click(function() {
$.ajax({
url: 'YOUR ROUTE HERE',
dataType: 'HTML',
success: function (data) {
$('#your-div').html(data);
}
});
});
//create a view users.html.twig or something like that...
{% if users is defined and users is not empty %}
{% for user in users %}
Name: {{ user.name }}
{% endfor %}
{% else %}
<p class="error">No data!</p>
{% endif %}
//add this line to top of your controller
use Symfony\Component\HttpFoundation\Request;
//add request variable to your action
public function printAction(Request $request)
{
//you want to get users via ajax right? so check if the request is ajax or not
if($request->isXmlHttpRequest()) {
// Get all users
$users = $this->getDoctrine()->getRepository('ModelBundle:Users')->findAll();
//render a view and pass it as variable
return $this->renderView('ModelBundle:Default:users.html.twig', ['users'] => $users);
}
}
Suppose in your view,
<div class="dynamic-data">
</div>
$.ajax({
url: "path to your print function",
type: "POST",
dataType: "HTML",
async: false,
data: {"u": url},
success: function(data) {
$(".dynamic-data").html(data);
// here directly manipulate the data in controller or get the data in success function and manipulate .
}
});
in print function instead of return print the data
Use jquery ajax() function to render data to html tag.The best way is to create a generic methon as follow and class it with url and div id
function renderPartialInDiv(url, divID) {
$.ajax({
cache: false,
async: true,
type: "POST",
url: url,
data: null,
success: function (data) {
$(divID).html(data);
},
processData: false,
async: false
});

Categories