How to execute a method in AJAX with Symfony2 when passing JavaScript arguments? - ajax

I'm getting confused by AJAX/S2 when I need to pass some arguments retrieved with JavaScript to a method in the controller.
In my script I have at some point, I get the position var:
function handle_geolocation_query(position){
alert('Lat: ' + position.coords.latitude + ' ' +
'Lon: ' + position.coords.longitude);
$.when( getLakes(position.coords.latitude, position.coords.longitude)).done(function(result1) {
console.log(result1);
});
};
function getLakes(lat, long) {
return $.ajax({
url: "{{ path('getLakes') }}",
data: { lat:lat, lng: lng },
dataType: 'jsonp'
});
};
then the router is set that way:
getLakes:
pattern: /lakes
defaults: { _controller: PondipGeolocBundle:Default:getLakesSurrounding }
And In my controller I'm supposed to return an array:
public function getLakesSurrounding($lat=0, $lng=0, $limit = 50, $distance = 50, $unit = 'km')
{
$lat = $this->getRequest()->get('lat');
$lng = $this->getRequest()->get('lont');
$return= array( '1'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'2'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'3'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'4'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'5'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4')
);
$return=json_encode($return); //jscon encode the array
return new Response($return,200,array('Content-Type'=>'application/json')); //make sure it has the correct content type
}
And then I'd like to pass it to another function that would set up the template with moustache to print it in the view (I'm not here yet ..)
My question is: I can't pass the needed lat and long data to my function. the router gets mad, the controller doesnt get anything and I don't get anything back from that script.
EDIT:I found my way to pass the variables, but I still can't get any response from my controller, nohing happen and the $.when does not execute any callback
I'm fairly new with AJAX, please advise.

Have a look at FOSJsRoutingBundle. With it you can use router from JS:
Routing.generate('my_route_to_expose', { "id": 10, "foo": "bar" });

Related

Site refresh time is long in laravel?

Hello and do not be tired!!
My admin panel pages are hard to load...It takes 15 seconds for the pages to load!!
The problem is with my routes!!!
Because when I define the path as follows, the pages load quickly :
Route::get('users/index', function () {
return view('admin.index');
});
But the route I have defined is as follows :
Route::group(['middleware' => ['auth' , 'InfoFolder' , 'verified' , 'Roles'] , 'prefix' => 'users/'] , function(){
Route::get('{url}', [UrlController::class , 'urlpanel'])->name('users_url');
});
And the control I have defined :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UrlController extends Controller
{
//
public function urlpanel($url ){
$admin = "admin";
$pages = "admin.pages";
$charts = "admin.pages.charts";
$examples = "admin.pages.examples";
$forms = "admin.pages.forms";
$mailbox = "admin.pages.mailbox";
$tables = "admin.pages.tables";
$UI = "admin.pages.UI";
$link_panel = [
'index' => "$admin.index",
'list_users' => "$admin.list_users",
'index3' => "$admin.index3",
'calendar' => "$pages.calendar",
'widgets' => "$pages.widgets",
'chartjs' => "$charts.chartjs",
'flot' => "$charts.flot",
'inline' => "$charts.inline",
'404' => "$examples.404",
'500' => "$examples.500",
'blank' => "$examples.blank",
'invoice-print' => "$examples.invoice-print",
'invoice' => "$examples.invoice",
'lockscreen' => "$examples.lockscreen",
'login' => "$examples.login",
'profile' => "$examples.profile",
'register' => "$examples.register",
'product_add' => "$forms.product_add",
'editors' => "$forms.editors",
'general' => "$forms.general",
'compose' => "$mailbox.compose",
'mailbox' => "$mailbox.mailbox",
'read-mail' => "$mailbox.read-mail",
'data' => "$tables.data",
'simple' => "$tables.simple",
'buttons' => "$UI.buttons",
'general' => "$UI.general",
'icons' => "$UI.icons",
'sliders' => "$UI.sliders",
];
if(!in_array($link_panel[$url] , $link_panel)){
return abort(404);
}
return view($link_panel[$url]);
}
}
How can I increase the loading speed of my website?
The project has been uploaded to Localhost
:)
Try to check the middlewares you are using. Maybe in one of the middlewares there is some time consuming action.

Where is the file after create by "$service->spreadsheets->create($requestBody)"

Thank you very much for reading this, its quite long!
I run my function:
public function createSpreadSheet()
{
$client = $this->getClient();
$service = new \Google_Service_Sheets($client);
// TODO: Assign values to desired properties of `requestBody`:
$requestBody = new \Google_Service_Sheets_Spreadsheet();
$response = $service->spreadsheets->create($requestBody);
echo '<pre>', var_export($response, true), '</pre>', "\n";
}
I got a result:
Google_Service_Sheets_Spreadsheet::__set_state(array(
'collection_key' => 'sheets',
'developerMetadataType' => 'Google_Service_Sheets_DeveloperMetadata',
'developerMetadataDataType' => 'array',
'namedRangesType' => 'Google_Service_Sheets_NamedRange',
'namedRangesDataType' => 'array',
'propertiesType' => 'Google_Service_Sheets_SpreadsheetProperties',
'propertiesDataType' => '',
'sheetsType' => 'Google_Service_Sheets_Sheet',
'sheetsDataType' => 'array',
'spreadsheetId' => '1QlBQo_YHQpiiMBWn6b6wSMVWkiFRx4grJhPParXUUSU',
'spreadsheetUrl' => 'https://docs.google.com/spreadsheets/d/1QlBQo_YHQpiiMBWn6b6wSMVWkiFRx4grJhPParXUUSU/edit',
'internal_gapi_mappings' =>
array (
),
modelData' =>
array (
),
'processed' =>
array (
),
'properties' =>
Google_Service_Sheets_SpreadsheetProperties::__set_state(array(
'autoRecalc' => 'ON_CHANGE',
'defaultFormatType' => 'Google_Service_Sheets_CellFormat',
'defaultFormatDataType' => '',
'iterativeCalculationSettingsType' => 'Google_Service_Sheets_IterativeCalculationSettings',
'iterativeCalculationSettingsDataType' => '',
'locale' => 'en_US',
'timeZone' => 'Etc/GMT',
'title' => 'Untitled spreadsheet',
'internal_gapi_mappings' =>
array (
),
'modelData' =>
array (
),
'processed' =>
array (
),
'defaultFormat' =>
Google_Service_Sheets_CellFormat::__set_state(array(
'backgroundColorType' => 'Google_Service_Sheets_Color',
'backgroundColorDataType' => '',
'bordersType' => 'Google_Service_Sheets_Borders',
'bordersDataType' => '',
'horizontalAlignment' => NULL,
'hyperlinkDisplayType' => NULL,
'numberFormatType' => 'Google_Service_Sheets_NumberFormat',
'numberFormatDataType' => '',
.........
.........
))
I access to the link it returned:
'https://docs.google.com/spreadsheets/d/1QlBQo_YHQpiiMBWn6b6wSMVWkiFRx4grJhPParXUUSU/edit'
it gives me this 'request access' page, then I press the request access
I open my email and get this:
Your message wasn't delivered to xxxxxx#xxxxxxxx.iam.gserviceaccount.com because the domain admanager-1x3x71x4x27x4.iam.gserviceaccount.com couldn't be found. Check for typos or unnecessary spaces and try again.
Is there something wrong and what should I do? I just want to open the file and check where it is.
Thank you very much!

change status active/inactive using ajax in yii2

[
'attribute' => 'status',
'format' => 'html',
'value' => function ($data) {
if($data->status==true) {
return Html::a("Inactive", "#", ['id' => $data->id, 'class' => 'a_status']);
}
else {
return Html::a("Active", "#");
}
]
The problem is, this code is not returning "id" attribute in link. So, wanted to know if this is currect way to put link in grid view or can someone point me correct way?'
Thx in advance.
Your code is missing one closing parenthesis and a change in format key's value -
Try -
[
'attribute' => 'status',
'format' => 'raw', //It was 'html' before
'value' => function ($data) {
if($data->status==true) {
return Html::a("Inactive", "#", ['id' => $data->id, 'class' => 'a_status']);
}
else {
return Html::a("Active", "#");
}
} //missing parenthesis
]
Well, you are missing a lot of code. Here are some observations.
*) I am using this kind of definition for the column
'value'=>function ($model, $key, $index, $widget) {
I am not sure if it makes a difference, try it this way maybe this is the problem.
Other things:
*) why are you using return
Html::a("Inactive", "#", ['id' => $data->id, 'class' => 'a_status']);
and not something like
Html::a("Inactive", ['change-status', 'status' => 'active', 'id' => $data->id], ['class' => 'a_status']);
You are creating in this way the link with the proper url already. If somebody does not have javascript enabled it will still work for them, just with a refresh.
Now you can create a global ajax function that you can reuse with ease for a lot more screens.
Now the actionChangeStatus function can end like this
if(Yii::$app->request->getIsAjax()) {
Yii::$app->response->format = 'json';
return ['success' => true];
} else {
return $this->redirect(['index']);
}
My ajax looks like this
jQuery.ajax({
"type": "GET",
"url": element.attr('href'),
"cache": false,
})
.success(function ( response ) {
$.pjax.reload({container: "#main-pjax", async:false, timeout: 4000});
});

Additional attributes not working

I am trying to add the following 2 additional attributes through API. I am not getting any error, however it is not getting uploaded. It would be great if some one could give me a suggestion.
catalogProductAdditionalAttributesEntity AdAtrributeEntity = new catalogProductAdditionalAttributesEntity();
associativeEntity[] AdditionalAttributes = new associativeEntity[2];
associativeEntity AdditionalAttributeOne = new associativeEntity();
associativeEntity AdditionalAttributeTwo = new associativeEntity();
AdditionalAttributeOne.key = "color";
AdditionalAttributeOne.value = "green";
AdditionalAttributeTwo.key = "size";
AdditionalAttributeTwo.value = "xl";
AdditionalAttributes[0] = AdditionalAttributeOne;
AdditionalAttributes[1] = AdditionalAttributeTwo;
AdAtrributeEntity.single_data = AdditionalAttributes;
ProductEntity.additional_attributes = AdAtrributeEntity;
MyService.catalogProductUpdate(Mylogin, SKU, ProductEntity, null, null)
I know this is older, but I found a solution. 'single_data' and 'multi_data' need to have an array inside it that has the arrays of attributes.
product_data = {
'name' => self.get_attribute_value('name'),
'description' => self.get_attribute_value('description'),
'short_description' => self.get_attribute_value('short_description'),
'weight' => self.get_attribute_value('weight'),
'status' => self.get_attribute_value('status'),
'categories' => compose_categories,
'url_key' => self.get_attribute_value('url_key'),
'price' => self.get_attribute_value('price'),
'additional_attributes' => { 'single_data' => { items: compose_attribute_values }}
}
In the example, I named the additional array 'item', hoever, you can call it whatever you want. I used 'item' because the API returns many values like that. The additional attributes look something like this in PHP:
...
'additional_attributes' = array(
'single_data' => array(
'item' => array(
[0] => array(
'key' => 'some_attribute_code',
'value' => 'some_attribute_value'
)
[1] => array(
'key' => 'some_other_attribute_code',
'value' => 'some_other_attribute_value'
)
)
)
)
...
This work for add additional_attributes:
'additional_attributes' => array(
'single_data' => array(
array(
'key' =>'manufacturer',
'value' => '10'
)
)
)
Example for Java (Apache XML-RPC client + Gson):
I have attribute manufacturer with option: Adidas (ID: 318)
Product entity:
...
#SerializedName("additional_attributes")
private Map<String,Map<String,String>> additionalAttributes;
...
// getters + setters
...
code:
...
Map<String,String> attribute = new HashMap<>();
attribute.put("manufacturer", "318");
Map<String,Map<String,String>> additionalAttributes = new HashMap<>();
additionalAttributes.put("single_data", attribute);
product.setAdditionalAttributes(additionalAttributes);
...
then do product.update api request
p.s: of course it's a little bit weird, but you can wrap that with some facade

How to "print" a theme during AJAX request (Drupal)

When users click on a button (with id graph), I'd like to fill the default Drupal content div (<div class="content">) with a graphael instance.
The JavaScript:
jQuery(document).ready(function($) {
$('#toggle #graph').click(function() {
$.ajax({
url: "http://www.mysite.com/?q=publications/callback",
type: 'POST',
data: {
'format' : 'graph'
},
success: function(response) {
$('div#content div.content').html(response);
}
});
});
});
The PHP:
$items['publications/callback'] = array(
'type' => MENU_CALLBACK,
'title' => 'All Publications Callback',
'page callback' => '_process_publications',
'page arguments' => array(t('journal')),
'access callback' => TRUE,
);
which leads to the page callback: (I'm concerned with the if code block)
function _process_publications($venue) {
if( isset($_POST['format']) && $_POST['format'] == "graph" ){
_make_bar_chart($venue);
}
elseif( isset($_POST['format']) && $_POST['format'] == "list" ) {
_make_list($venue);
}
else{
return("<p>blah</p>");
}
}
and finally the function called within the callback function:
function _make_bar_chart($venue) {
// get active database connection
$mysql = Database::getConnection();
// if connection is successful, proceed
if($mysql){
// do stuff
$graphael = array(
'method' => 'bar',
'values' => $ycoordinates,
'params' => array(
'colors' => $colors,
'font' => '10px Arial, sans-serif',
'opts' => array(
'gutter' => '20%',
'type' => 'square',
),
'label' => array(
'values' => $xcoordinates,
'isBottom' => true,
),
),
'extend' => array(
'label' => array(
'values' => $ycoordinates,
'params' => array('attrText' => array(
'fill' => '#aaa',
'font' => '10px Arial, sans-serif',
)),
),
),
);
return theme('graphael', $graphael);
}
// else, connection was unsuccessful
else{
print("<p>bad connection</p>");
}
}
THE PROBLEM: returning a theme doesn't really send anything back to the AJAX request (unlike print statements). I tried to print the theme, but that produces a white screen of death. How would I generate the graph without printing something?
Much thanks to nevets on the Drupal forums for the helpful hint: http://drupal.org/node/1664798#comment-6177944
If you want to use AJAX with Drupal, you are best off actually using Drupal-specific AJAX-related functions. In my theme's page.tpl.php file, I added the following to make the links which would call AJAX:
<?php
// drupal_add_library is invoked automatically when a form element has the
// '#ajax' property, but since we are not rendering a form here, we have to
// do it ourselves.
drupal_add_library('system', 'drupal.ajax');
// The use-ajax class is special, so that the link will call without causing
// a page reload. Note the /nojs portion of the path - if javascript is
// enabled, this part will be stripped from the path before it is called.
$link1 = l(t('Graph'), 'ajax_link_callback/graph/nojs/', array('attributes' => array('class' => array('use-ajax'))));
$link2 = l(t('List'), 'ajax_link_callback/list/nojs/', array('attributes' => array('class' => array('use-ajax'))));
$link3 = l(t('Create Alert'), 'ajax_link_callback/alert/nojs/', array('attributes' => array('class' => array('use-ajax'))));
$output = "<span>$link1</span><span>$link2</span><span>$link3</span><div id='myDiv'></div>";
print $output;
?>
When one of the links above is clicked, the callback function is called (e.g. ajax_link_callback/graph):
// A menu callback is required when using ajax outside of the Form API.
$items['ajax_link_callback/graph'] = array(
'page callback' => 'ajax_link_response_graph',
'access callback' => 'user_access',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
.. and the callback to which it refers:
function ajax_link_response_graph($type = 'ajax') {
if ($type == 'ajax') {
$output = _make_bar_chart('journal');
$commands = array();
// See ajax_example_advanced.inc for more details on the available commands
// and how to use them.
$commands[] = ajax_command_html('div#content div.content', $output);
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);
}
else {
$output = t("This is some content delivered via a page load.");
return $output;
}
}
This replaces any HTML within <div class="content"> with the graphael chart returned from _make_bar_chart above.

Resources