Convert an Array with objects in in it into a Json - php

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.

Related

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

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

How to retrieve a parameter from ajax to laravel API Controller

I have an API that requires a string parameter. I want to take the query parameter to the controller and process there. I tried $ajax_data = Input::get('query'); but it didnt work. Searched the same question but cant find a decent answer. Current error is $ajax_data is empty.
My ajax request:
const sendAPIRequest = function (csrf, f) {
$.ajax({
async: false,
url: 'api/apitest',
method: 'get',
data:{
query:"select?facet=on&q=*:*&rows=1&json.facet={Categories:{type:terms,field:price,limit:3}}"
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + tkid);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('X-CSRF-TOKEN', csrf.trim());
},
success: function (data) {
f(data);
},
error: function(xhr) {
//Do Something to handle error
}
});
};
My Controller API part:
public function apitest(){
$ajax_data = Input::get('query');
$user_type = UserAuthorizationHelper::user_authorization();
if ($user_type == Authorities::EDIT_ORGANISATIONS) {}
$query = new GuzzleHttp\Client();
try {
$response = $query->request('GET',SolrController::$url.$ajax_data);
} catch (GuzzleHttp\Exception\GuzzleException $e) {}
$data = $response->getBody()->getContents();
return response()->json(json_decode($data));
}
You are having a problem in this line:
$ajax_data = Input::get('query');
When you are making a request, Request object is sent with the data.
So, instead of Input replace it with Request's object, and you will get the desired output.
Something like this:
// Don't forget to import the Request's namespace
public function apitest(Request $request)
{
$ajax_data = $request->get('query');
// ... Rest of your code
}

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

Laravel response()->json in custom class return empty string

i have one problem, and I cant solve it.
In my controller i have method:
public function deleteImg(Request $request, $id) {
$image_id = $request->input('imgId');
$image_src = $request->input('imgSrc');
AdImages::delete($id, $image_id, $image_src);
}
Inside of AdImages class I have static method:
public static function delete($id, $image_id, $image_src) {
return response()->json(['status' => 'error', 'message' => 'Error occurred. Please try again.']);
}
And here is ajax:
$.ajax({
url: '/dashboard/ad/{{ $ad->id }}/remove-image',
type: 'POST',
data: {imgId: imgId, imgSrc: imgSrc},
success: function(data) {
console.log(data);
}
})
Problem is if i return response i got nothing, empty string. But if i var dump(response()->...) i see object i need.
Any ideas/suggestions ?
Thank you
Your controller method isn't actually returning anything to the browser. You should put the return json response call in your controller method, not in your model.
I'd also advise you not to name model methods "delete", as that's an Eloquent keyword.
Add a return to AdImages call:
return AdImages::delete($id, $image_id, $image_src);
thank you guys.
that was the problem :)
And yes, it would be smart to rename delete to something else.

How do I use the PUT feature in REST

Using this git-hub library:
http://github.com/philsturgeon/codeigniter-restserver
How do I use the PUT feature to save its data?
example: example.com/put/some-data/some-data/...
you can use it like this: but take in count that PUT is less commonly used and not supported by most browsers
function somename_put()
{
$data = array('somedata: '. $this->put('some-data'));
$this->response($data);
}
You can do it with an ajax request e.g.
(assumes use of jQuery)
$.ajax({
url: '/index.php/my_controller/somedata',
type: 'PUT',
success: function(result) {
console.log(result);
}
});
According this (link: https://github.com/philsturgeon/codeigniter-restserver/blob/master/application/libraries/REST_Controller.php#L915), $this->put only return if passed a param to it (so that works: $username = $this->put('username')). But in REST_Controller, $this->_put_args is protected so, you will extend this class and can access it like: $params = $this->_put_args.
In short (this is just an example, you may improve it as you need);
<?php
// route: /api/users/123
class Users extends REST_Controller
{
...
// update a user's data
public function user_put() {
$params = $this->_put_args;
// you need sanitize input here, "db" is a pseudo
$username = $db->escape($params['username']);
$userpass = $db->escape($params['userpass']);
$db->update(array(
'username' => $username,
'userpass' => $userpass
), (int) $params['id']);
if (!$db->error) {
// suppose right code should be 201 for PUT
$this->response('Created', 201);
} else {
$this->response('Internal Server Error', 500);
}
}
}
?>
<script>
// Some ajax library
Ajax("/api/users/123", {
method: "PUT",
data: {username:"John", userpass:"new pass"},
onSuccess: function(){ console.log("Success!"); }
...
});
</script>

Categories