Getting POST parameter on symfony 2.2 and Ajax - ajax

I am using Ajax.
And here is the Ajax-call part of my twig template,
$.post('{{path('acme_member_delScore')}}',
{data1: num }, //I assured that 'num' has right data in javascript
function(response){
if(response.code == 100 && response.success){//dummy check
//do something
console.log(response.id);
}
}, "json");
And my routing.yml contains,
acme_member_delScore:
pattern: /delScore
defaults: { _controller: AcmeMemberBundle:Default:delScore}
While the action in my Controller is defined as follow,
public function delScoreAction()
{
$request = $this->container->get('request');
$id = $request->query->get('data1');// but $id is null
// ...
Do you have any idea why my $id variable (in delScoreAction) is always set to null?
Is there anything I have to check?

Try something like this
$id = $request->request->get('data1');

Related

Display result of search within view

I have a page where I display all my clients. It uses paginate and only displays 16 clients per page. As such I have provided realtime search functionality.
When a search is perform, the option selected from the results triggers the following
select: function (event, ui) {
$.ajax({
url: "/returnClient",
type: "GET",
datatype: "html",
data: {
value : ui.item.value
},
success: function(data) {
$('.container').fadeOut().html(data.html).fadeIn();
}
});
}
That essentially calls the following function
public function returnClient(Request $request)
{
if($request->ajax()){
$selectedClient = $request->input('value');
$client = Client::where('clientName', $selectedClient)->first();
$html = View::make('clients.search', $client)->render();
return Response::json(array('html' => $html));
}
}
If I output the client variable above, I can see all the details for this particular client. This is then being passed to the partial clients.search.
Within clients.search, if I do
{{dd($client)}}
I get Undefined variable: client. Why does it not get the parsed Object within the view?
Many thanks
The issue is that you are improperly passing $client to the view. The Views documentation shows how to properly pass data via an associative array. The API docs confirm that an array is what is expected.
Do this instead:
public function returnClient(Request $request)
{
if($request->ajax()){
$selectedClient = $request->input('value');
$client = Client::where('clientName', $selectedClient)->first();
$html = View::make('clients.search', ['client' => $client])->render();
return Response::json(array('html' => $html));
}
}
Also, as a point of habit you may want to consider using dump() instead of dd().

How to put many parameters in a route in FOSJsRoutingBundle?

I have a route with many parameters; but when I generate it with FOSJsRoutingBundle the navigator takes just the first parameter and generate a 404 Error
Example:
var id = $(this).val();
var name = "aaa";
$.ajax({
url: Routing.generate('my_route', {
'id': id,
'name': name
}),
// rest of code
This syntax is it correct ?
EDIT 1 :
My route
my_route:
path: /homepage/{id}/{name}
defaults: { _controller: AcmeBundle:Personal:changename}
options:
expose: true
Just incase someone else comes across this (I just wasted several hours)... If the parameter you are passing in matches the default, Routing.generate doesn't include the parameter.
For example:
Controller:
/**
* #Route("/plc/data/{systemID}/{tagID}", name="web_plc_data", options = { "expose" = true })
*/
public function indexAction(Request $request, $systemID=1, $tagID=16)
{
}
From twig:
var url = Routing.generate('web_data', { systemID: 10, tagID: 16 });
Will generate route:
/plc/data/10 (note 'tagID' parameter is ignored)
From twig:
var url = Routing.generate('web_data', { systemID: 10, tagID: 17 });
Will generate route:
/plc/data/10/17 (tagID parameter now included as it doesn't match default)
Best solution I could find was to set default parameters to NULL in the route, then initialise in the function itself (if null, set to some value).
Ie:
/**
* #Route("/plc/data/{systemID}/{tagID}", name="web_plc_data", options = { "expose" = true })
*/
public function indexAction(Request $request, $systemID=null, $tagID=null)
{
if ($systemID==NULL)
{
$systemID = 1;
}
if ($tagID==NULL)
{
$tagID = 16;
}
}
Implementation makes sense, just a bit confusing as it causes unexpected behavour.
I don't know why the navigator doesn't take the second parameter but i have solved the problem like this :
var id = $(this).val();
var name = "aaa";
var url = Routing.generate('my_route', {
id: id,
}) + "/" + name;
$.ajax({
url: url,
// rest of code
In case someone else is dealing with the same issue, I just added the option expose true to the route since i'm using FOSJsRoutingBundle to generate the route in javascript, and everything work fine.
Here is the route definition:
/**
* #Route("/show/{id}/{toValidate}", name="contribution_show", methods={"GET"}, options={"expose"=true})
*/
public function show(Contribution $contribution, $toValidate): Response
And here is my ajax call to generate the route:
url : Routing.generate('contribution_show', {id: id, toValidate: toValidate }),

Simple ajax in laravel 4

i have following code
ajax
//ajax edit button
$('.edit_button').on('click', function(e) {
e.preventDefault();
var id_produk = $(this).attr('id');
$.ajax({
type : "POST",
url : "editproduk",
data : id_produk,
dataType: 'JSON',
success : function(data) {
alert('Success');
console.log(data);
},
error: alert('Errors')
});
});
i always get messagebox error
and don't know where i'm missing,
because in chrome - inspect element - console not give any clue
my route
Route::post('/account/editproduk', array(
'as' => 'edit-produk-post',
'uses' => 'AccountController#postEditProduk'
));
my controller
public function postEditProduk() {
if (Request::ajax()) {
return "test test";
}
}
extended question
i running my script well after using return Response::json() like this
$id_produk = Input::get('id_produk');
$produk = Produk::findOrFail($id_produk);
return Response::json($produk);
and access it in view by this script
success : function(data) {
alert('Success');
console.log(data["name-produk"]);
}
but if i want to return array json like
$id_produk = Input::get('id_produk');
$produk = Produk::findOrFail($id_produk);
$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk);
return Response::json(array($produk, $spesifikasi));
i can't access it in view like this...
success : function(data1, data2) {
alert('Success');
console.log(data1["name-produk"] - data2["title-spek"]);
}
how to access json array
extended question update
if i'm wrong please correct my script
because i get a litle confused with explenation
is this correct way to return it?
Response::json(array('myproduk' => 'Sproduk', 'data2' => 'testData2'));
result
console.log(produk["myproduk"]);
--------------------------------
Object {id_produk: 1, nama_produk: "produk1", deskripsi: "desc_produk"
console.log(produk["data2"]);
--------------------------------
testData2
and i still don't have idea how to print nama_produk in my_produkarray
Question 1:
Why is this code not sending JSON data back.
public function postEditProduk() {
if (Request::ajax()) {
return "test test";
}
}
Answer: Because this is not the right way to send the JSON data back.
From the Laravel 4 docs, the right way to send JSON data back is linked. Hence the correct code becomes:
public function postEditProduk() {
if (Request::ajax()) {
return Response::json("test test");
}
}
Question 2:
Why am I not able to access the data in data1 and data2
success : function(data1, data2) {
alert('Success');
console.log(data1["name-produk"] - data2["title-spek"]);
}
Answer: Because this is not the right way to catch the JSON data. The right way to send is given in the Laravel 4 API reference docs.
static JsonResponse json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)
As you can see the method json takes string or array as the first parameter. So you need to send all your data in the first parameter itself (which you are doing). Since you passed only one parameter, you have to catch only 1 parameter in your javascript. You are catching 2 parameters.
Depending on what $produk and $spesifikasi is, your data will be present in one single array. Lets say that $produk is a string and $spesifikasi is an array. Then your data on the javascript side will be this:
[
[0] => 'value of $produk',
[1] => array [
[0] => 'value1',
[1] => 'value2'
]
]
It would be best if you print the log your entire data and know the structure. Change your code to this:
success : function(data) {
console.log(data.toString());
}
This will print your entire data and then you can see the structure of your data and access it accordingly. If you need help with printing the data on your console, google it, or just let me know.
I sincerely hope that I have explained your doubts clearly. Have a nice day.
Edit
extended question answer:
Replace this line:
$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk);
With this:
$spesifikasi = SpesifikasiProduk::where('id_produk', '=', $id_produk)->get();
Without calling the get() method, laravel will not return any value.
Then access your data in javascript like this:
console.log(JSON.stringify(data));
This way you will get to know the structure of your data and you can access it like:
data[0]["some_key"]["some_other_key"];
In your controller you're returning text while your ajax request awaits json data, look at these lines of codes, I think you should get your answer:
if(Request::ajax()) {
$province = Input::get('selectedProvince');
//Get all cites for a province
if ($cityList = City::where('province_id','=', $province)) {
return Response::make($cityList->get(['id', 'name']));
}
return Response::json(array('success' => false), 400);
}

Codeigniter rest issue with backbone

I just started using rest library wrote by Phil Sturgeon. I started using it by writing some simple examples. I short of get 'post' and 'get' work, but not for put and delete. I have some questions based on the code below.
// a simple backbone model
var User = Backbone.Model.extend({
urlRoot: '/user',
defaults:{
'name':'John',
'age': 17
}
});
var user1 = new User();
//user1.save(); // request method will be post unless the id attr is specified(put)
//user1.fetch(); // request method will be get unless the id attr is specified
//user1.destroy(); // request method will be Delete with id attr specified
In my CI REST controller
class User extends REST_Controller
{
public function index_get()
{
echo $this->get(null); //I can see the response data
}
public function index_post()
{
echo $this->post(null); //I can see the response data
}
public function index_put()
{
}
public function index_delete()
{
}
}
Basically, the get and post in the controller will be called when I save a model or fetch a model. With a id specified in the model, I can make a put or delete request to the server using model.save() and model.destroy(). however, I got a server error. it looks like index_put or index_delete can not be called. does anyone know How I can handle:
put request in the controller
delete request in the controller
get a single record with id specified
From the git, I only saw him to list index_post and index_put. there is no index_put and index_delete demo. should anyone can help me out? thanks
I faced the same exact problem, it looks like that DELETE, PUT, PATCH methods are not fully supported by browsers/html/server yet. You may want to look at this stack overflow question: Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
A simple solution would be to change the methodMap of backbone line 1191 to the following:
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'POST', //'PUT',
'patch': 'POST', //'PATCH',
'delete': 'POST', //'DELETE',
'read': 'GET'
};
and then include the action type as an attribute of the model
var Person = Backbone.Model.extend({
defaults:{
action_type : null,
/*
* rest of the attributes goes here
*/
},
url : 'index.php/person'
});
now when you want to save a model, do the following
var person = new Person({ action_type: 'create' });
person.set( attribute , value ); // do this for all attributes
person.save();
in the application/controllers folder you should have a controller called person.php with class named Person extending REST_Controller, that has the following methods:
class Person extends REST_Controller {
function index_get() { /* this method will be invoked by read action */ }
/* the reason those methods are prefixed with underscore is to make them
* private, not invokable by code ignitor router. Also, because delete is
* might be a reserved word
*/
function _create() { /* insert new record */ }
function _update() { /* update existing record */ }
function _delete() { /* delete this record */ }
function _patch () { /* patch this record */ }
function index_post() {
$action_type = $this->post('action_type');
switch($action_type){
case 'create' : $this->_create(); break;
case 'update' : $this->_update(); break;
case 'delete' : $this->_delete(); break;
case 'patch' : $this->_patch(); break;
default:
$this->response( array( 'Action '. $action_type .' not Found' , 404) );
break;
}
}
}
Having said that, this solution is an ugly one. If you scroll up in the backbone implementation, you will find the following code at line 1160:
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
params.type = 'POST';
which means you need to set the emulate options of backbone configurations. add the following lines to your main.js
Backbone.emulateHTTP = true;
Backbone.emulateJSON = true;
To test the effect of that, I created a simple model and here are the results
you need a controller called Api in applications/controllers folder, in a file named api.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH.'/libraries/REST_Controller.php';
class Api extends REST_Controller
{
function index_get()
{
$this->response(array("GET is invoked"));
}
function index_put()
{
$this->response(array("PUT is invoked"));
}
function index_post()
{
$this->response(array("POST is invoked"));
}
function index_patch()
{
$this->response(array("PATCH is invoked"));
}
function index_delete()
{
$this->response(array("DELETE is invoked"));
}
}
and in your js/models folder, create a model called api_model.js
var Api = Backbone.Model.extend({
defaults:{
id: null,
name: null
},
url: "index.php/api/"
});
var api = new Api();
api.fetch({ success: function(r,s) { console.log(s); } }); // GET is invoked
api.save({},{ success: function(r,s) { console.log(s); } }); // POST is invoked
//to make the record old ( api.isNew() = false now )
api.save({id:1},{ success: function(r,s) { console.log(s); } }); // PUT is invoked
api.destroy({ success: function(r,s) { console.log(s); } }); //DELETE is invoked
I don't know how to do patch, but hope this helps.
Edit
I found out how to do patch, which is not included in the REST implementation of code ignitor. In REST_Controller line 39, you will find the following,
protected $allowed_http_methods = array('get', 'delete', 'post', 'put');
you need to add 'patch' at the end, to accept this method, also, after doing that add this code
/**
* The arguments for the PATCH request method
*
* #var array
*/
protected $_patch_args = array();
also, you need to add the following code to parse patch arguments:
/**
* Parse PATCH
*/
protected function _parse_patch()
{
// It might be a HTTP body
if ($this->request->format)
{
$this->request->body = file_get_contents('php://input');
}
// If no file type is provided, this is probably just arguments
else
{
parse_str(file_get_contents('php://input'), $this->_patch_args);
}
}
Now, according to backbone docs, you need to pass {patch: true} to send a PATCH method, when you call the following line, you execute a patch:
api.save({age:20},{patch: true, success: function(r,s) { console.log(s); } });
// PATCH is invoked

Basic implementation of ajax in magento

I am a newbie in magento and trying to implement ajax,but can't find a proper tutorial to follow. Could anyone provide me some reference or guide me to where i would be able to find it?
Don't know a tutotial but I can explain you bit what I implemented in a project a month back.
I created a controller on which we can fire an AJAX request on a specific action. In this case the getoptionsAction in the IndexController of our custom Offerte module.
The getoptionsAction in my controller takes a product_id and loads the options for the product. It builds the HTML and echo's this on function end.
In phtml file I have following code to invoke the AJAX request and update html-object in frontend:
function get_options(prod_id){
var product_options = $('product_options');
var prod_id = $('product').getValue();
new Ajax.Updater('product_options',
'<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getoptions',
{ method: 'get',parameters: {prod_id: prod_id, type: 'get_regular_options' } ,
onCreate: function(){
$('loading-img-options').show();
},
onComplete: function (t) {
$('loading-img-options').hide();
$('product_options').show();
}
});
}
the above function uses Ajax.Updater. You can also use Ajax.Request to get the result to juggle with.
function stripslashes(str) {
return str.replace(/\\'/g,'\'').replace(/\"/g,'"').replace(/\\\\/g,'\\').replace(/\\0/g,'\0');
}
function get_products(){
product = $('product');
cat_id = $('category').value;
new Ajax.Request('<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getproducts',
{method: 'get', parameters: {cat_id: cat_id, mode: 'offerte'},
onCreate: function(){
$('product-loading').show();
$('product_options').hide();
},
onSuccess: function(t) {
resp = jQuery.parseJSON(t.responseText);
$('prod-container').innerHTML = resp.options ? stripslashes(resp.options) : '<?php echo $this->__('No options found') ?>';
$('product-loading').hide();
}
});
}
(please note I use JQuery to parseJSON. You can also use String.evalJSON, but I was lazy here :-)
Using Ajax.Request you need to return the result from the controller as JSON. I used the code below in my controller to return JSON to our phtml to use in the onSuccess Callback function above:
$this->getResponse()->setBody(Zend_Json::encode($result));
Hope this is of any help

Resources