AngularJS UI-router pass param from view to state resolve - php

I am trying to pass params in ui-sref then access it to state resolve.
HTML View
ui-sref="reservation({check_in: check_in, check_out: check_out})"
I am trying to get the params passed in ui-sref to the resolve.
This is some code in my controller when I don't yet use a resolve.
$http.get('server/getFilteredRooms.php', {
params: {
check_in: data.check_in,
check_out: data.check_out
}
}).then(function(res){
Then I tried to implement resolve because I want to wait for the data to get before rendering the view. In that way, I believe, I will not encounter undefined due to data from http function is not yet returned.
JS (app.js)
.state("reservation", {
url: "/reservation",
templateUrl: "pages/reservation.html",
controller: "ReservationController",
resolve : {
promiseObj : function($http){
return $http({
method: 'GET',
url: 'server/getFilteredRooms.php',
params: {
check_in: check_in,
check_out: check_in
}
});
}
}
})
And I am trying to access in my PHP file like this.
PHP
$check_in = $_GET['check_in'];
$check_out = $_GET['check_out'];

To receive those parameters in the state's resolve, at first, you need to declare those in the state's configuration. Change the state's configuration, and introduce a params key as follows:
.state("reservation", {
url: "/reservation",
templateUrl: "pages/reservation.html",
controller: "ReservationController",
params: {
check_in: null,
check_out: null
},
resolve: ...
Then, modify the resolver as follows:
promiseObj: function($http, $transition$){
var params = $transition$.params();
return $http({
method: 'GET',
url: 'server/getFilteredRooms.php',
params: {
check_in: params.check_in,
check_out: params.check_in
}
});
}
This way, your resolver knows that it should extract the parameters' values from the URL and passes those to the HTTP call.

Related

Send a post request to a php page using ajax

I'm trying to send a text that is typed via ajax to a php page that will make a query using that text that is received. I want to know how to send the value of variable nmClient to the php page. I tried the following code and the return was 500 (Internal Server Error). I'm using the framework Symfony
Jquery
var name = $("#name").val();
$.ajax({
url: "../search",
type: "POST",
data: {'name':name},
dataType: "json"
}).done(function(response) {
console.log(response);
}).fail(function(jqXHR, textStatus ) {
console.log("Request failed: " + textStatus);
}).always(function() {
console.log("done");
});
PHP
public function searchAction(Request $resquest)
{
if ($request->isXMLHttpRequest()) {
$name = $request->get('name');
return new JsonResponse(array('name' => $name));
}
return new Response('This is not ajax!', 400);
}
I believe you're trying to access the parameter name in the incorrect place. The get() method is available on the ParameterBag instance, not the Request instance. Try the following:
$name = $request->request->get('name');
Per the docs here:
Each property is a ParameterBag instance (or a sub-class of), which is a data holder class:
request: ParameterBag;
query: ParameterBag;
cookies: ParameterBag;
attributes: ParameterBag;
files: FileBag;
server: ServerBag;
headers: HeaderBag.
All ParameterBag instances have methods to retrieve and update their data:
get() Returns a parameter by name.
Here is the example from that same page:
// the query string is '?foo[bar]=baz'
$request->query->get('foo');
In the docs example case, the parameters are passed via the GET method as a query string but they access them via the query ParameterBag instance. You'll want to use the request Parameter Bag instance since your parameters are passed via the POST method.

400 Bad Request after sending AJAX post request in Yii 2

I want to post data via ajax to some specific controller like this :
<script>
var myUrl = "<?php echo Url::to(['table/edit']); ?>";
</script>
$.ajax({
type : "POST",
url : myUrl,
data: {id: userID},
success : function(response) {
alert("Table is editted");
}
});
And in the controller I want to get this posted data and do some thing else.
But when I try this I am getting an error "400 (Bad Request)".
If someone can help it would be great! Thanks!
Just add csrf like :
<script>
var myUrl = "<?php echo Url::to(['table/edit']); ?>";
</script>
$.ajax({
type : "POST",
url : myUrl,
data: {id: userID,_csrf:'<?=\Yii::$app->request->csrfToken?>'},
success : function(response) {
alert("Table is editted");
}
});
yii\web\BadRequestException (represents HTTP error with code 400) can be thrown in following cases:
1) Unable to verify your data submission. CSRF validation is enabled and failed. I don't think it's the reason in your case, because it's enabled by default and included in meta tags. When using jQuery, you don't have to send it manually.
2) Missing required parameters.
If you have parameters without default values, for example:
public function actionTest($someParam)
{
...
}
If you didn't pass someParam, exception will be thrown.
3) Invalid JSON data in request body.
If you send JSON as parameter and it's not a valid JSON.
4) Invalid data received for parameter. Thrown during binding parameters to action:
if ($param->isArray()) {
$args[] = $actionParams[$name] = (array) $params[$name];
} elseif (!is_array($params[$name])) {
$args[] = $actionParams[$name] = $params[$name];
} else {
throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
'param' => $name,
]));
}
Last two are rarely meet, especially the last one (can't remember even single time when I met it).
These should be all possible cases at the moment, I did global search through sources just to make sure.

How to call custom action in controller(laravel) using AngularJS

I am using laravel 5.
I have a custom action in my controller. By custom I mean it is not used by the resource object in angular. The following is the code of my controller.
class ServicesController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function extras()
{
// code here
}
}
This is my service code in the angular script.
(function() {
'use strict';
angular
.module('bam')
.factory('myservice', myservice);
function myservice($resource) {
// ngResource call to the API for the users
var Serviceb = $resource('services', {}, {
update: {
method: 'PUT'
},
extras: {
method: 'GET',
action: 'extras'
}
});
function getExtras(){
return Serviceb.query().$promise.then(function(results) {
return results;
}, function(error) {
console.log(error);
});
}
}
})();
Now, the query() here will send the request to the index method in the laravel controller. How will I access the extras() action in the getExtras() method?
It looks like you're almost there try out the example below I tried to use what you have in your question, and added a few other custom endpoints as examples. You'll want a base URL set up similarly to the example so you can feed it an id out of your payload so $resource can set up your base CRUD. Otherwise to make custom routes using the same resource endpoint you can add some extra actions like you have in your question, but apply your customization on the base endpoints URL.
.factory('ServicesResource', ['$resource',
function ($resource) {
// Parameters used in URL if found in payload
var paramDefaults = {
id: '#id',
param: '#param'
}
// Additional RESTful endpoints above base CRUD already in $resource
var actions = {
custom1: {
method: 'GET',
url: '/api/services/custom',
},
custom2: {
method: 'GET',
url: '/api/services/custom/:param',
},
extras: {
method: 'GET',
url: '/api/services/extras'
}
update: {
method: 'PUT'
}
}
// Default URL for base CRUD endpoints like get, save, etc
return $resource('/api/services/:id', paramDefaults, actions);
}])
Now you can dependency inject the factory and use it like this:
var payload = {param:'someParam'};
ServicesResource.custom(payload).$promise.then(function(response){
// handle success
}, function(reason) {
// handle error
});
Or for Extras:
ServicesResource.extras().$promise.then(function(response){
// Handle success
}, function(reason) {
// Handle error
});
In Laravel you're route might be something like this:
Route::get('services/{param}/custom', 'ServicesController#custom');
Or for extras like this:
Route::get('services/extras', 'ServicesController#extras');
I got what I wanted using $http.
function getExtras(){
return $http.get('/services/extras').success(function (results) {
return results;
});
}
But, that would be nice if anyone suggest me how to do it with Serviceb.query().$promise.then.

Resource POST Acting as GET method angularjs

I am trying to learn angularjs, so today i tryed using resource.
looks like it all went good at syntax and method calling,
Please open the FIDDLE first
Initially i tried with $http POST, looks like it worked
$http({url: '/register.php', method: "POST",
data: { 'message' : {userName:'ravi'}}});
With PHP code:
$data = file_get_contents("php://input");
$objData = json_decode($data);
....
....
//insert stmt to mysql
Next, When i tried with $resource, with
In registerController
authProviders.saveUser($scope.newuser);
In authProviders service :
return $resource(AppConstants.ServerPath + '/register.php/:registerId',
{registerId: '#registerId'},{
saveUser: {
method: 'POST',
params: { message: {userName:'ravi'} },
isArray: false
}
});
The call is going like get method.
Can any Body of you please Correct me in these.
My question question :
When you fill the form and submit which is in fiddle, the URL in the console look like
http://fiddle.jshell.net/register.php?message=%7B%22userName%22:%22ravi%22%7D
Which looks like GET method, even through the method type is POST
Thanks in Advance.
Remove params from Resources:
return $resource(AppConstants.ServerPath + '/register.php/:registerId',
{registerId: '#registerId'},{
saveUser: {
method: 'POST',
params: { message: {userName:'ravi'} }, //Remove This
isArray: false
}
});
If you want to use the GET method, then you have to say
method: 'GET',
params: { message: {userName:'ravi'} },
If you want to make it as POST, then
method: 'POST',
data: { message: {userName:'ravi'} },

Sending json to symfony controller

I need to pass json data to my Symfony Controller. My ajax function looks like this:
var data = '{"firstname":"John"}';
$.ajax({
type: "POST",
url: save_url, //path to controller action
data: {json:data},
success: function(response) {
// Do something
}
});
In my controller, I try to get my data through:
public function createAction(Request $request) {
$data = $this->getRequest()->get('firstname');
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
Just to see if this works, I send $data to be echoed in a template. In Firebug I can see the data being sent and everything seems to work, but $data is empty and nothing is echoed. Where am I doing this wrong?
EDIT: When I check the response in Fireburg console, I see my data there, in place, but it never appears in the template. var_dump($data) tells that $data is null. So, it seems data is being sent but the controller ignores it.
As Marek noticed:
$this->getRequest()
already returns the request object, you're accessing the request property of the request, that doesn't add up. Either try:
$data = $this->request->get('json');
Or use:
$data = $this->getRequest()->get('json');
You can, of course assign the return value of $this->getRequest() to a variable, and call the get method on that var from there on end... anyway, here's my initial answer, it does contain some more tips, and considerations you may find useful:
You should be able to get the data this way, though AJAX requests + echoing in a template? That does sound a bit strange. I don't see you passing the $data variable to a $this->render call anywhere.
This is a copy-paste bit from a controller action in one of my projects. It works just fine there:
public function indexAction()
{
if (!$this->getRequest()->isXmlHttpRequest())
{//check if request is AJAX request, if not redirect
return $this->redirect(
$this->generateUrl('foo_bar_homepage')//changed this, of course
);
}
$id = $this->getRequest()->get('id',false);//works fine
However, I can't begin to grasp why you're doing this:
var data = '{"firstname":"John"}';
Why not simply go for:
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {firstname: 'John'},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
Then, in your controller you're able to:
$this->getRequest()->get('firstname');//it should be John
You could even pass {json:{firstname: 'john'}} as the data param to $.ajax, the only difference in your controller will be, that you have to do this:
$data = $this->getRequest()->get('json');
$firstName = $data['firstname'];
That should work just fine, unless there's somthing you're not telling us :)
RECAP:
This is what I'd write:
public function createAction()
{//no Request param in controller
if (!$this->getRequest()->isXmlHttpRequest())
{//no ajax request, no play...
$this->redirect(
$this->generateUrl('homepage_route')
);
}
$data = $this->getRequest()->get('firstname');
//return json response:
return new Response(json_encode(array('dataReceived' => $data));
//return rendered HTML page:
return $this->render('MyBundle:Counter:test.html.twig', array(
'data' => $data
));
}
Of course, then the JS code should read:
$.ajax({
type: "POST",
url: 'route/to/create'
data: {firstname:'John'},
success: function(response)
{
console.log(response);
}
});
I have tested this, and I see no reason why this shouldn't work. It works just fine for me...
Please note this was #EliasVanOotegem original example but there are some obvious steps missing
in the controller i'm reading a few replies as in "I cannot see how this works as i'm getting null" this is because your not correctly keying your object.
i.e.
var data = { name : 'john' };
$.ajax({
type: "POST",
url: url,//post how you get this URL please...
data: {json : data},//jQ will sort this out for you
success: function(response)
{
console.log(response);
}
error: function()
{
console.log('an error occured');
console.log(arguments);//get debugging!
}
});
as you can now see accessing the requerst object like
$request->get('json');
refers to the post key for the json data
Is the content what you're trying to retrieve, neither params nor headers.
Try:
$request->getContent();
In your case $request->request->get('json') should do.

Categories