I have fixed the issue with ajax on typo3. Now comes another issue in hand. This time is related to returning the object found in the action to Javascript. So I tell you what I do exactly.
here is first my ajax call function:
function getContent(id)
{
console.log("Starting process ...");
$.ajax({
async: 'true',
url: 'index.php',
type: 'POST',
data: {
eID: "ajaxDispatcher",
request: {
pluginName: 'listapp',
controller: 'Pays',
action: 'getMyCompanys',
arguments: {
'id': id
}
}
},
dataType: "json",
success: function(result) {
var data = JSON.parse(result)
console.log(data.nom);
},
error: function(error) {
console.log(error);
}
});
}
and here is the "getMyCompanys" action:
public function getMyCompanysAction()
{
$argument = $this->request->getArguments('id');
$company = $this->entrepriseRepository->findBypays(2); // just to test with the id 2
$result = (array) $company;
return json_encode($result);
}
Now on the console I get this Output:
{"\u0000*\u0000dataMapper":{},"\u0000*\u0000persistenceManager":{},"\u0000*\u0000query":{},"\u0000*\u0000queryResult":null}
So at the first glance , i thought the object was not passed to the javascript , but when I tried to add an attribute to the object $company ($company->att = 'val';)
I get this output :
{"\u0000*\u0000dataMapper":{},"\u0000*\u0000persistenceManager":{},"\u0000*\u0000query":{},"\u0000*\u0000queryResult":null**,"att":"val"}**
notice that the added attribute and its value get showed
so I now I'm convinced that there is something wrong with the object. I am also 100 % sure that the method findBypays(2); is working, I tried it in a listAction.
I don't really know what could be the problem :/
Just for your Information: this is part of an extension in typo3 that I developed myself using JBuilder
well after struggling for a long time , I tried a trick and it worked and it proved me that the json_encode does not return an object in typo3 eventhough I applied the :
$object->toArray() or (array) $object
to the object , so my solution was :
$companies = array();
foreach ($this->adresseRepository->findByland($id) as $company)
{
$companies[] = array(
'uid' => $company->getUid(),
'firma' => $company->getFirma(),
'strasse' => $company->getStrasse(),
'plz' => $company->getPlz(),
'ort' => $company->getOrt(),
'land' => $company->getLand(),
'telefon' => $company->getTelefon(),
'email' => $company->getEmail(),
'webseite' => $company->getWebseite()
);
}
return json_encode($companies);
and It Worked ;)
Related
newbie here.
I am trying to understand how I need to structure asynchronous calls within my controller to fit my specific use case:
Consider the following code snippet from an Angular Module in "service.js" within my project:
function getSearchObjects(projectName, title) {
var payload = JSON.stringify({
"title": title
});
var request = $http({
method: 'post',
url: URL + '/search/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
};
function runQuery(projectName, fromDate, toDate, sort, direction, columns) {
var from = Date.parse(fromDate);
var to = Date.parse(toDate);
var payload = JSON.stringify({
"fromDate": from,
"toDate": to,
"sort": sort,
"direction": direction,
"columns": columns
});
console.log(payload);
var request = $http({
method: 'post',
url: URL + '/query/' + projectName,
data: payload
});
return request.then(handleSuccess, handleError);
}
function handleSuccess(response) {
return response.data;
};
function handleError(response) {
if (!angular.isObject( response.data ) || !response.data.error) {
return( $q.reject( "An unknown error occurred." ) );
}
return $q.reject( response.data.error );
};
});
Within my controller, I am trying to troubleshoot the following function:
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date, objectProperties.sort, objectProperties.direction, objectProperties.columns)
},
function(error) {
console.log(error);
});
};
getSearchObjects matches a title ($scope.selected.search) selected in my UI and grabs the following more detailed object from an API call:
{ title: 'Duplication Example',
sort: '#_traac-timestamp',
direction: 'desc',
columns: [ '#_traac-remote_ip', 'c-platform-m-distinct-id_s', '_type' ] }
I am trying to grab the properties returned from getSearchObjects and pass them along with a few user selected values from my UI to runQuery, which then returns data from a database to the user, but when I check the values passed to runQuery using the above logic in my controller, I get the following values. All of the objectProperties values I am attempting to pass to runQuery are undefined:
project_name: "Example Project"
start_date: 1499770800000
end_date: 1499943600000
sort: undefined
direction: undefined
columns: undefined
I have been trying to debug this, but I am too new to using Angular and asynchronous calls to really understand what I am doing wrong. My best guess currently is that I am calling runQuery before the values retrieved from getSearchObjects are attached to objectProperties. Either that or I am incorrectly referencing the properties within the objectProperties variable.
Could someone help me troubleshoot this issue, and better understand what I am doing wrong?
Thank you in advance for your help!
When you do this:
var objectProperties = some async function...
You are assigning the promise of the async function to the variable, not the result of it.
The result is coming in the .then, like you declared:
.then(function(result) { ... }
So, instead of objectProperties.sort, objectProperties.direction, objectProperties.columns, try using result.sort, result.direction, result.columns :)
If you are new to Promises, take a look at this simple, but great tutorial.
EDIT
Based on your comment, you are receiving, inside the response.data, the following object:
{"objectMatch": {
"title": "doc-event",
"sort": "#_traac-timestamp",
"direction": "desc",
"columns": [
"m-doc-name_s",
"m-user_s",
"m-full-action-type_s",
"m-event-action-descriptor_s"
]}
}
So you have: response > data > objectMatch > properties you want.
The response.data you are extracting on your handleSuccess function:
function handleSuccess(response) {
return response.data;
};
So here, your result is response.data, containing the property objectMatch.
$scope.submit = function() {
var objectProperties = exportsStorageService.getSearchObjects($scope.selected.project.name, $scope.selected.search)
.then(function(result) {
...
},
...
If all of that is correct, you should be able to access the values you want using result.objectMatch.<sort, direction or columns>, like:
exportsStorageService.runQuery($scope.selected.project.name, $scope.selected.start_date, $scope.selected.end_date,
result.objectMatch.sort, result.objectMatch.direction, result.objectMatch.columns)
I need to retrieve a value from an async service to add as a parameter to every rest call. The casService.getProxyTicket() is an $http call...
I have the following code :-
myFactories.factory('myFactory', [
'Restangular'
, 'casService'
, function (Restangular
, casService) {
return Restangular.withConfig(function (config) {
config.setBaseUrl('https://host:port/somecontext/rest');
config.addFullRequestInterceptor(function (element
, operation
, route
, url
, headers
, params
, httpConfig) {
... What do I need to do here?
casService.getProxyTicket(url).then(function(st){
console.log('proxyTicket = ' + st.data.ticket);
});
params.ticket = ?????? <= st.data.ticket
...
return {
element: element
, headers: headers
, params: params
, httpConfig: httpConfig
}
});
}).service('myCollection');
}]
);
...thanks in advance!!!!
Ok, my lack of understanding coming from a backend developer's background...
This can/should NOT be done this way! I was trying to make the call to get a proxy ticket synchronous.... DON'T DO IT!
What I did was to rearrange my code thus ...
function readItem(id) {
var endpoint = myFactory.one(id);
return casService.getProxyTicket(endpoint.getRestangularUrl())
.then(function (response) {
return endpoint.get({ticket: response.data.proxyTicket});
}).then(function (response) {
return response.plain();
});
}
...works like a charm!
I have a controller that takes a List<int> and I am calling from AJAX. The controller is hit, but the parameter is always null.
My controller:
public ActionResult MinorAreas(List<int> majorareas)
{
// ...
}
jQuery call:
function onChange(e)
{
var cur = this.value(); // an array of numbers like [2,4,7,9]
$.ajax({
cache: false,
type: "GET",
traditional: true,
url: "#(Url.RouteUrl("GetMinorAreas"))",
data: { "majorareas": cur},
success: function (data) {...},
error: function (xhr, ajaxOptions, thrownError) {... }
});
}
Route definition:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
new[] { "ABC.ZZZ.Controllers" }
);
Using fiddler, I can see that the URI is built correctly:
# With an array of [2]
http://localhost:15536/minorAreas?majorareas=2&_=1450307693166
# With an array of [2,3,9]
http://localhost:15536/minorAreas?majorareas=2&majorareas=3&majorareas=9&_=1450308261808
I've already looked at this question about passing arrays to a controller with a List<int> parameter, but the solution doesn't seem to work for me. What am I doing wrong?
It looks like the network request is being generated correctly. The problem is in the route definition:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas", majorareas=new List<int>() },
new[] { "ABC.ZZZ.Controllers" }
);
majorareas=new List<int>() is going to ensure that majorareas is always an empty list, even when it otherwise would be populated!
You don't have to define parameters here; the method definition in the controller does that. Leave it off, and it should work fine:
routes.MapLocalizedRoute(
"GetMinorAreas",
"minorAreas",
new { controller="ProSearch", action="MinorAreas" },
new[] { "ABC.ZZZ.Controllers" }
);
I am a beginner in Javascript and Jquery and I am trying to get data from the server, access them and display them without reloading the page with Ajax and Laravel 5.
So here is what I do:
My controller:
public function get_media_details(){
$media_id = $_POST['media_id'];
$media_details = Media::find($media_id);
print_r ($media_details);
}
My JS function:
function show_media_detail(media_id){
$.ajax({
url: "get_media_details",
type:"POST",
data: { media_id: media_id },
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
success:function(data){
console.log(data);
},
error:function(){
console.log("No data returned");
}
});
}
And the result of console.log(data):
"App\Media Object
(
[table:protected] => media
[fillable:protected] => Array
(
[0] => name
[1] => feed_url
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[name] => TechCrunch
[description] => Breaking technology news and analysis.
[link] => http://techcrunch.com/
[feed_url] => http://techcrunch.com/feed/
[thumbnail] => Rll0vnSkWk3bvTTWdthYzagXGnLHt9EHpU3Qe8XK
)
etc...
But know I am trying to access specific value of this object, like for example, the name of my media.
I tried many things and searched a lot, but I keep failing miserably...
Any help would be greatly appreciated !
Thank you
change this
print_r ($media_details);
to
return $media_details;
in js file
... success:function(data){
for (var x in data){
console.log(data.description); // should output description
}
....
I'm using jquery.couchdb.js to query my CouchDB database. The view I want to query has both map and reduce functions within. When sending the basic query as shown below:
$(document).ready(function() {
view_name = db_name+'/jobs_by_mod_stat'
options = {'group': 'true' , 'reduce': 'true' };
mod_stat = {};
$db.view(view_name , {
success: function(data) {
console.log(data)
for (i in data.rows) {
console.log(data.rows[i].value);
}
},
error: function(e) {
alert('Error loading from database: ' + e);
}
});
});
I see a sensible log for the data, indicating the query has been successful. However, changing the line:
$db.view(view_name , {
To
$db.view(view_name , options, {
I don't get a success outcome from the Ajax query, but an error message is not shown either. Firebug shows the query being sent, and the JSON data returned looks sensible:
{"rows":[
{"key":["template","completed"],"value":2},
{"key":["template","running"],"value":2},
{"key":["template","waiting"],"value":6}
]}
But the success function is not entered. Any ideas why I'm seeing this behaviour, I did wonder if it's a bug in jquery.couch.js (I have couchdb 1.1.0).
Cheers.
I've had a bit of trouble myself with the list function, until I went and looked through the source code of jquery.couch.js (the online documentation I found at http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/ seems to be outdated).
Basically, the parameters for view and list are different, the list having an extra parameter for the options, instead of having everything under the same parameter as with views.
View:
$.couch.db('yourdb').view('couchapp/' + viewName, {
keys: ['keys here'],
success: function (data) {
}
});
List:
$.couch.db('yourdb').list('couchapp/' + listName, viewName, {
keys: ['keys here']
}, {
success: function (data) {
}
});