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'} },
Related
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.
I'm trying to read $_POST array posted through AJAX in a controller action using Yii::$app->request->post(), but something strange happens.
jQuery:
`
function renderGridView() {
var formId = $('#input-field :input[value!=""]');
// extract values. Make sure to send _csrf token
$.ajax({
url: "?r=value-search%2Fsearch", //this one works
method: 'POST',
data: {
searchData: formId.serializeArray(),
},
success: function(response) { //JSON array is returned.
/*$('#resultGrid').DataTable( {
data: [
response['provider']
],
columns: [
response['columns']
]
}); */
console.log(response);
}
})
}
`
PHP Controller action:
public function actionSearch() {
$data = \Yii::$app->request->post('searchData');
$tt; $svalue;
if(count($data) === 0) {throw new UserException('data is emptry');}
echo var_dump($data);
}
And here's the issue, the code above works just fine. But when I'm trying to echo $data my custom UserException 'data is empty' is thrown, instead of PHP's 'trying to pass array as a string', which I'd normally expect. What is causing this? Why does post() behave like this? Is there a technical reason to it?
just change
data: {
searchData: formId.serializeArray(),
},
to
data:formId.serialize(),
you should use ActiveForm to create your form using your model and the names will be automatically assigned to inputs which include the convention ModelName[field_name] apart from this you haven't shown your form but in your action you are getting the searchData in the post() array so I assume you have the data being posted as
[
searchData=>[
field_1=>value,
field_1=>value,
field_1=>value,
field_1=>value,
]
]
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.
I have seen many examples, but for whatever reason, none seem to work for me.
I have the following sent from a app, via ajax, to a php file. This is how it looks when its sent:
obj:{"ClientData":
[{
"firstName":"Master",
"lastName":"Tester",
"email":"me#me.com",
"dob":"1973-01-22",
"age":"51",
}],
"HealthData":
[
"condition : Prone to Fainting / Dizziness",
"condition : Allergic Response to Plasters",
],
"someData":
[{
"firstName":"Male",
"lastName":"checking",
}]
}
Code as is:
{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}
This comes in one long line into a php file, here is the code:
<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
//var_dump($_POST['obj']);
$Ojb = json_decode($_POST['obj'],true);
$clientData = $Ojb['ClientData'];
$healthData = $Ojb->HealthData;
$someData = $Ojb->someData;
print_r($clientData['firstName']);
?>
No matter what I have tried, I am unable to see any of the information, I don't even get an error, just blank! Please can someone point me in the right direction.
Thank you :)
UPDATE
Here is the code that creates the object:
ClientObject = {
ClientData : [
{
firstName : localStorage.getItem('cfn'),
lastName : localStorage.getItem('cln'),
email : localStorage.getItem('cem'),
dob : localStorage.getItem('cdo'),
age : localStorage.getItem('cag'),
pierceType : localStorage.getItem('cpt'),
street : localStorage.getItem('cst'),
city : localStorage.getItem('cci'),
county : localStorage.getItem('cco'),
postcode : localStorage.getItem('cpc')
}
],
HealthData : health,
PiercerData : [
{
firstName : localStorage.getItem('pfn'),
lastName : localStorage.getItem('pln'),
pierceDate : localStorage.getItem('pda'),
jewelleryType : localStorage.getItem('pjt'),
jewelleryDesign : localStorage.getItem('pjd'),
jewellerySize : localStorage.getItem('pjs'),
idChecked: localStorage.getItem('pid'),
medicalChecked: localStorage.getItem('pmh'),
notes: localStorage.getItem('poi')
}
]
};
And here is how its sent:
function senddata() {
$.ajax({
url: 'http://domain.com/app.php',
type: 'POST',
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
data: 'obj='+JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
There are a few things that will cause problems:
why dataType: 'jsonp'? If you don't intend to utilize jsonp, don't instruct jQuery to do this. See the docs: https://api.jquery.com/jQuery.ajax/
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
'obj='+JSON.stringify(ClientObject), this will guarantee invalid json.
For reference, have a look at this question: jQuery ajax, how to send JSON instead of QueryString on how to send json with jquery.
That said, try the following:
function senddata() {
$.ajax({
url: 'app.php',
type: 'POST',
crossDomain: true,
contentType: 'application/json; charset=utf-8"',
data: JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
And in app.php use
$input = json_decode(file_get_contents('php://input'));
to get the data. Use it like:
var_dump($input->ClientData[0]->firstName); // => string(6) "Master"
$Ojb = json_decode($_POST['obj'],true);
makes it array so u need to get them using array index instead of object
UPDATE1
With your update here how it could be done
$str ='{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}' ;
$obj = json_decode($str,true);
echo $obj["ClientData"][0]["firstName"];
You can get other elements as above
UPDATE2
You are sending the data as JSONP and this will make the request as
?callback=jQuery17108448240196903967_1396448041102&{"ClientData"
Now you are also adding data: 'obj=' which is not correct.
You can simply send as json not jsonp
and on the php file you can do as
$Ojb = json_decode(file_get_contents('php://input'),true);
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.