Get data from controller and then print it via ajax - php

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

Related

passing multiple id into one ajax function

I want to run the same js ajax function on multiples id, so I could return the specific information from my database. Here it did run through "id="test" but it returns them to all of it. How do I make them return to its own "id"
html
<div>
<p class="postbutton" id="test_1" > </p> \\supposed to return 1, but it returns 3//
<p class="postbutton" id="test_2" > </p> \\supposed to return 2, but it returns 3//
<p class="postbutton" id="test_3" > </p> \\supposed to return 3, but it returns 3//
</div>
my scripting function
$(".postbutton").each(function () {
x = $(this).prop('id').replace(/[^\d.]/g, '') // converting it to a set of ID to be passed to my controller
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller, Laravel stuff */
data: {_token: CSRF_TOKEN, message: x},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data)
{
$(" p[id^='test']").html(data.msg);
}
});
});
Use $(this).html() otherwise, for each ajax call, $(" p[id^='test']").html(data.msg) will be call even the last ajax call. So the last call has 3 as answer. So it updates the two first ajax call.
$(".postbutton").each(function () {
var context = this
x = $(context).prop('id').replace(/[^\d.]/g, '') // converting it to a set of ID to be passed to my controller
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller, Laravel stuff */
data: {_token: CSRF_TOKEN, message: x},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data)
{
$(context).html(data.msg);
}
});
});
Since ID is attribute which wont be changes in your case - try replace .prop with .attr() to get the value of ID.
Also matching that you inside success function will return all possible matches - in this case 3
Also it will be good if you use already founded ID for matching element in success function like
$(`#test_${x}`).html(data.msg);
First to store your all id in array.
after pass this array in your ajax function.
like this:-
var id_list=[];
$(".postbutton").each(function () {
x = $(this).prop('id').replace(/[^\d.]/g, '') // converting it to a set of ID to be passed to my controller
id_list.push(x);
});
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller, Laravel stuff */
data: {_token: CSRF_TOKEN, message: id_list},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data)
{
$(" p[id^='test']").html(data.msg);
}
});

Passing ajax data to blade to use in php query

I have a modal which opens on click:
jQuery('.calendar-day-update-edit-trigger').click(function(event){
var targetDate = jQuery(this).attr('data-day');
jQuery('.updater-date-edit').html(targetDate);
jQuery('.hidden-date-input-edit').val(targetDate);
$.ajax({
method: "get",
url: "/admin/days/getdata/"+targetDate,
data: { 'EID': targetDate,},
})
});
I want to send the data to a blade file so I can query my database.
public function getData($getData){
$data = Day::where('sale_at', $getData)->first();
return $data;
}
Hello,
If you want to return data from your controller to your template, you must return your data in json.
After this, you can use the success method in your ajax call to get the data from your controller and affect these data to an or more HTML elements in your blade template.
In your JS:
$.ajax({
method: "get",
url: "/admin/days/getdata/"+targetDate,
data: { 'EID': targetDate,},
success: function(data) {
$('#your_html_element').val(data);
}
})
In your PHP:
header('Content-Type: application/json');
echo json_encode($data);
In your blade template:
<div id="your_html_element"></div>

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

Laravel: Send Data to Controller via AJAX Without Form

I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically.
Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.
Here's what i'm doing:
Route:
Route::post('section/saveContactItems', 'SectionController#saveContactItems');
Controller:
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
JS:
$('button').on("click", function (evt) {
evt.preventDefault();
var items = [];
var id = $("#id").val();
var languageID = $("#languageID").val();
var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };
$.ajax({
url: "/section/saveContactItems",
type: "POST",
data: data,
cache: false,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response)
{
console.log(response);
}
});
});
What am i doing wrong? How can i accomplish this?
UPDATE: Thanks to #ShaktiPhartiyal's answer (and #Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following #Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:
data: JSON.stringify(data),
You do not need to use
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
You have to do the following:
public function saveContactItems()
{
$id = Input::get('id');
$type = Input::get('type');
$items = Input::get('items');
$languageID = Input::get('languageID');
}
and yes as #Sanchit Gupta suggested you need to send the CSRF token with the request:
Methods to send CSRF token in AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you use this approach you need to set a meta tag like so:
<meta name="csrf-token" content="{{csrf_token()}}">
or
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
UPDATE
as #Sanchit Gupta pointed out use the Input facade like so:
use Input;

laravel ajax action url with parameters

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.

Categories