How to pass variables from jquery fetch function to symfony routes.yaml? - php

So I want to call a controller in symfony by passing in my route declared in routes.yaml with a jquery fetch function and I want to pass to variables from jquery to the controller. How can I do that ?
Here's my jquery. I call this route and I want to pass the two variable on top with it.
var longitudde = lonLat[0];
var latudde = lonLat[1];
fetch('/weather_request)
.then(function(response) {
return response.json();
}).then(function(json) {
// ...
});
To pass those variables to routes.yaml in Symfony:
weather_request:
path: /weather_request
controller: App\Controller\WeatherController::weather
methods: [get]
defaults:
longitude: longitude
latitude: latitude
To finaly pass them in the weather function in WeatherController:
public function weather($longitude, $latitude)
{
return $this->render('weather/index.html.twig', ['weatherInfos' => $this->weatherService->getWeather($longitude, $latitude)]);
}
So how can I pass the longitude and latitude from jquery fetch to the controller here ? I'm new to Symfony so I could be completely wrong.

I guess this can help you :
$.ajax({
url: '{{path('weather_request')}}',
type: 'GET',
data: {
longitude: lonLat[0],
latutide: lonLat[1],
},
success: function(response) {
//called when successful
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
In your controller :
use Symfony\Component\HttpFoundation\Request;
public function weather(Request $request)
{
if ($request->isXMLHttpRequest()) {
$longitude = $request->query->get('longitude');
$latutide = $request->query->get('latutide');
}
}

for me I use it like that:
In Js:
const obj = {
"longitudde":lonLat[0],
"latudde":lonLat[1]
}
fetch('/weather_request',
{
method:'POST',
headers: {
'Content-Type':'application/json'
},
body:JSON.stringify(obj)
}).then(resp => {
return resp.json();
}).then(res => {
console.log(res)
//...
})
}
In Controller route annotations,but you can use with Route.yaml:
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
/**
* #Route("/weather_request", methods={"POST"})
*
*/
public function weather(Request $request)
{
$data = json_decode($request->getContent());
$longitude = $data->longitudde;
$latitude = $data->latudde;
return $this->render('weather/index.html.twig',
[
'weatherInfos' => $this->weatherService
->getWeather($longitude, $latitude)
]);
}

Related

Convert an Array with objects in in it into a Json

Actually I'm working with Symfony 2.8, an I'm trying to use AJAX to get information of an id given.
This is how I use Ajax in my html.twig :
$.ajax({
url: '{{ (path('questionsByAudit')) }}',
type: "POST",
dataType: "json",
data: {
"idAudit": $(this).attr('data-id')
},
async: true,
success: function (data)
{
console.log(data);
alert(data);
}
});
This Is my URL in my routing.yml:
questionsByAudit:
path: /QuestionsByAudit
defaults: { _controller: FSABundle:FsaPlan/FsaPlanByAuditor:getQuestions }
And this is the function in the controller:
public function getQuestionsAction(Request $request )
{
$em = $this->getDoctrine()->getEntityManager();
if($request->request->get('idAudit')){
$idAudit = $request->request->get('idAudit');
$Audit = $em->getRepository('FSABundle:FsaAudits')
->findBy(array('idAudit'=>$idAudit));
return new JsonResponse($Audit);
}
}
THe problem is that the next function returns this:
And this is what I get when I print the result in an alert:
This is what I get in console.log:
NOTE: I've read that the way to return the information of the controller to the ajax call should be as a JSON, but I think that what I get in $Audit is an array with objects inside, I don't know how to return that information to the Ajax correctly.
Any Idea or suggestion how can I get it?
In Controller Function Return Json Response.
use Symfony\Component\HttpFoundation\Response;
$result['success'] = "1";
$result['data'] = $data;
$result['message'] = "Successfully Update";
$response = new Response(json_encode($result));
return $response;
one simple approach would be to implement JsonSerializable on the objects you want to encode
class FsaAudits implements \JsonSerializable {
// ... all other content
public function jsonSerialize() {
return (array)$this; // this might only contain an empty array
}
}
however, it's better to actually control what is output (don't want truely internal data to leak):
public function jsonSerialize() {
return [
'idAudit' => $this->idAudit,
//...
];
}
another way would be to use Symfony's Serializer component.

Can't pass parameters using AJAX + Symfony 4

I'm using AJAX to request client names from my DB using autocomplete() inside an input #descricao. It requests a route that I created inside Symfony 4 (/acao).
The problem is that I'm trying to set a parameter (/acao?parametro=clientname) but I'm get an error:
Could not resolve argument $parametro of
"App\Controller\DefaultController::filter()", maybe you forgot to
register the controller as a service or missed tagging it with the
"controller.service_arguments"?
I tried to change my routes.yaml:
acao:
path: /acao
controller: App\Controller\DefaultController::filter
methods: GET
but it didn't work.
script.js:
$( "#descricao" ).autocomplete({
source: function( parametro, response ) {
$.ajax({
url: '/acao',
dataType: "json",
data: {
parametro: $('#descricao').val()
},
success: function(data) {
response(data);
}
});
}
});
DefaultController:
/**
* #param string $parametro
* #return JsonResponse
* #Route("/acao", name="acao", methods="GET")
*/
public function filter(string $parametro){
$em = $this->getDoctrine()->getManager()->getRepository(Clients::class)
->createQueryBuilder('c')
->andWhere('c.name_fantasy ilike :parametro')
->setParameter('parametro','%'.$parametro.'%')
->getQuery()
->getArrayResult();
return new JsonResponse($em);
}
What am I doing wrong?
ANSWER:
I managed to make it work using POST and changing table name c.name_fantasy to values:
Controller:
/**
* #param Request $request
* #return JsonResponse
* #Route("/acao", name="acao", methods="POST")
*/
public function filter(Request $request){
$q = strtoupper(trim($request->request->get('parametro')));
$em = $this->getDoctrine()->getManager()->getRepository(Clients::class)
->createQueryBuilder('c')->select('c.name_fantasy AS value')
->andWhere('c.name_fantasy like :parametro')
->setParameter('parametro', '%'.$q.'%')
->getQuery()
->getArrayResult();
return new JsonResponse($em);
}
AJAX:
$( "#descricao" ).autocomplete({
source: function( parametro, response ) {
$.ajax({
url: '/acao',
dataType: 'json',
method: 'POST',
data: {
parametro: $('#descricao').val()
},
success: function(data) {
if (data.length > 0) {
response(data);
}
else {
data = '';
response(data)
}
},
});
}
});
Firstly, you dont need use routes.yaml for routing, if you use the Route Component:
Symfony\Component\Routing\Annotation\Route
So just delete that stuff from routes.yaml.
EDITED:
/**
* #param Request $request
* #return JsonResponse
* #Route("/acao", name="acao", methods="GET", options={"expose"=true})
*/
public function filter(Request $request)
{
//you should strip and trim the parameter, like (just basic):
$clientName = strip_tags(
trim($request->query->get('parametro'))
);
// ...
}
Where Request is Symfony\Component\HttpFoundation\Request <-- you need add to the use statements!
If this not working for you, with your original ajax (what in your question), try on this way:
// ...
let formData = new FormData();
formData.append("parametro", $('#descricao').val());
$.ajax({
url: '/acao',
// ...
data : formData,
// ...
JUST A TIP:
I recommend, use the symfony/bundles/FOSJsRoutingBundle. You can link your routes in js like this:
import Routing from '../../vendor/friendsofsymfony/jsrouting-bundle/Resources/public/js/router';
import Routes from '../../public/assets/js/fos_js_routes.json';
Routing.setRoutingData(Routes);
// ...
$.ajax({
//acao is your route name and you route in this case:
url: Routing.generate("acao"),
Dump the latest added routes, with this command:
php bin/console fos:js-routing:dump --format=json --target=public/assets/js/fos_js_routes.json
...

angular with mysql to fetch database

I have this working example where i have use $scope and $http in controller to fetch an col from database using get method in variable as given below
<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'quizdb.php'
}).then(function successCallback(response) {
// Store response data
$scope.users = response.data;
});
}]);
</script>
now i want this same thing in my factory service i have where i am using hardcoded array. i want to replace the hardcoded array with dynamic array.
with php i am getting an array of but the problem is that i dont know how to implement this thing in factory in angular
my factory is as follows
(function(){
angular
.module("htcssquiz")
.factory("DataService",DataService);
function DataService(){
var dataObj = {
turtleData: turtleData,
quizQuestions: quizQuestions,
correctAnswer : correctAnswer
};
return dataObj;
}
var correctAnswer = [1,2,3,0,2,0,3,2,0,3];
var quizQuestions = [
{
type: "text",
text: "How much can a loggerhead weigh?",
possibilities: [
{
answer: "Up to 20kg"
},
{
answer: "Up to 115kg"
},
{
answer: "Up to 220kg"
},
{
answer: "Up to 500kg"
}
],
selected: null,
correct: null
}
so i want to replace this correctAnswer array with dynamic one.
please help me i am new to angular . thank you in advance.
I am using this factory DataService in The List controller using $inject as follows
(function(){
angular
.module("htcssquiz")
.controller("listctrl", ListController);
ListController.$inject = ['quizMetric','DataService'];
function ListController(quizMetric,DataService){
var vm = this;
vm.quizMetric =quizMetric;
vm.data = DataService.turtleData;
vm.activeTurtle = {};
vm.changeActiveTurtle = changeActiveTurtle;
vm.activateQuiz =activateQuiz;
vm.search = "";
function changeActiveTurtle(index){
vm.activeTurtle = index;
}
function activateQuiz(){
quizMetric.changeState("quiz", true);
}
}
}) ();
This will require a change to both your controller AND your service. The controller will now use the service as if it were the $http call:
fetch.controller('userCtrl', ['$scope', 'DataService', function ($scope, DataService) {
DataService.getCorrectAnswer().then(function (response) {
// Store response data
$scope.correctAnswer = response.data;
});
}]);
Your service will now take responsibility for making the $http call:
DataService.$inject = ['$http'];
function DataService($http){
var dataObj = {
...
getCorrectAnswer : function() {
return $http({
method: 'get',
url: 'quizdb.php'
});
}
};
return dataObj;
}

Laravel 4.1.* AJAX response method

I'm trying to setup a simple POST method with AJAX, posting to a Laravel controller and processed.
The issue I am having is returning a response that the AJAX call understand and can use.
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
AJAX stuff to get form data:
$('#supplierChainCheckForm').submit(function( event ) {
event.preventDefault();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// As we're using the "csfrUnsafeMethod" of POST - we'll need to setup the csfr token to be passed between client and server:
$.ajaxSetup({
// This is standard before send method for the ajaxSetup() function:
beforeSend: function(xhr, settings) {
// If settings.type in $.ajax method is unsafe i.e., if it is 'POST' then we'll need to set X-CSRFToken in the xhr Request Header: omitted && sameOrigin(settings.url) currently;
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", $('meta[name="csrf-token"]').attr('content'));
}
}
});
// Get all the form inputs into an array:
var $inputs = $('#supplierChainCheckForm :input');
// We can now loop over all of the input names & values of the form:
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] ,'_token': '{{ csrf_token() }}'}
}).done(function(response) {
console.log(response.companyName);
});
});
ApplicationController.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication() {
if (!Input::get('companyName') == null) {
$company = Input::get('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}
However, combining all of the above gives me
console.log(response.companyName) as "undefined"
Please advise. Please note, I am using Laravel 4.1.*
Update function parameter as below;
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (!$request->input('companyName') == null) {
$company = $request->input('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}

Form AJAX post response cycle in Laravel 4.1.*

I have a rather old site that I have inherited as part of a new position - it's been built to Laravel 4.1.* version specs.
My issue is Response::json returning undefined variables in the response, using standard AJAX post method with all CSRF stuff and ajaxSetup() defined correctly.
application.blade.php
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] }, //This will carry the form data that is needed to be passed to the server.
success: function (response) {
console.log(response['companyName']); << THIS LINE RETURNS "undefined"
console.log(typeof response) << THIS LINE RETURNS string
},
error: function (response) {
console.log(response);
},
});
values['companyName'] returns what I input into the form. The above "response" simple chucks back html - so I think my routes might be incorrectly defined or incorrectly defined in the AJAX url param, perhaps? Here are the two applicable routes:
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
ApplicationController.php:
<?php
use Illuminate\Http\Request;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (Input::has('companyName')) {
$this->companyName = Input::get('companyName');
$data = [
'success': true,
'companyName': $this->companyName
];
return response()->json($data);
}
}
}
Any pro-tips would be greatly appreciated!
to check what your are missing in controller when posting or getting your result
usually which i follow
in blade.php
<.form method="post" action="{{url('supply-us/application')}}".>
{{csrf_field()}}
<.input type="text" name="companyName".>
<./form.>
remove dot try this it will help you to find missing thing in controller
in your blade
<.input type="text" name="companyName" id="companyName".>
in your ajax
var company = $('#companyName').val();
$.ajax({
type: 'POST',
url: 'supply-us/application',
data: { 'Company':company,'_token': '{{ csrf_token() }}' },
success: function (response) {
alert(data) // if this not work then try this alert(data.company)
},
error: function (response) {
console.log(response);
},
});
in your controller
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $req) {
if (!$req->get('Company')==null) {
$company = $req->get('Company');
return response()->json($company);
}else{
$company="no input give";
return response()->json($company);
}
}
}

Categories