CodeIgniter not receiving POST data - php

I already have a Codeigniter based RESTful api service which performs basic CRUD operations to the mySQL database. And now I'm trying to make a control panel with angularJS and Restangular.
I make a POST request like this:
HTML:
<form ng-submit="addUser()">
<input type="text" name="name" ng-model="newUser.name" placeholder="Enter Your Name" />
<input type="text" name="fact" ng-model="newUser.fact" placeholder="Enter A Fact" />
<input class="pure-button" type="submit" value="Send" />
</form>
JS:
$scope.addUser = function ()
{
var newuser = $scope.newUser;
Restangular.one("user").post(newuser).then(function(data) {
console.log(data);
})
}
PHP (Using Codeigniter's inpu class):
$data = array(
'name' => $this->input->post('name'),
'fact' => $this->input->post('fact')
);
And then it writes $data array to the database. But in database, values are always 0, which means the $data['name'] and $data['fact'] are empty.
I think i should handle the data in a diffrent way in PHP but how can i do that? Or what is the type of POSTed data?

try
$data = file_get_contents("php://input");
$data = json_decode($data,true);
:)

Related

Yii2 cannot change form response

So I am trying to work with an eccomerce site written in yii2, for the life of my I cannot understand how this promocode error logic works. So the cart controller has an action below in CartController.php
public function actionAddPromo()
{
$promocode = new Promocodes();
$insertType = $promocode->validatePromocode(Yii::$app->request->post('promo'));
if ($insertType =="3") {
$arr = [
'smallcart' => $this->renderPartial('small-cart'),
'bigcart-items' => $this->renderPartial('bigcart-items'),
'bigcart-totals' => $this->renderPartial('bigcart-totals')
];
return json_encode($arr);
} else {
return $insertType;
}
}
This appears to be called when a post request is sent to /cart/add-promo which occurs in this form here
<form action="#" id="promocode-form" method="get" class="apply-coupon">
<input class="search-field" id='promocode-value' data-page="cart"
required="required" type="text" placeholder="<?= Yii::t("app", "Coupon Code"); ?>" value=""/>
<input type="submit" class="button light-gray-bg " style="width:100px" value="<?= Yii::t("app", "Apply"); ?>">
</form>
The issue is that I am trying to change the error codes that come up. When the number is returned from the post request somehow "This promocode is expired" shows up but a CTRL F of the project shows no reference to this string hard coded. I have seen the modal that is modified to show up with this content but no luck in the main.php that houses it. I have inspected the onSubmit handler that is modified and sure enough it checks $trim(data) for if it is equal to 1-4 and responds with an error message. I assume this is auto-generated js by yii2/php but I cannot find the php that is responsible for creating this or where I can even look to find this.

Request form and POST in a single go?

Please excuse the poor title.
I am a total beginner and don't know the right terms to make it better.
I am trying to POST form data using PHP.
My problem is that before i POST the form data i need to get a value from the form, that is changing each time i request the page.
Please notice the second input, the value is auto generated and is a random number each time i request the form.
Here is my form.php:
<?php
if(!isset($_REQUEST['submit_btn'])){
echo '
<form action="'.$_SERVER['PHP_SELF'].'" method="POST">
<input type="text" name="user_name" id="user_name">
<input type="hidden" name="a_random_password" value="'.(rand(10,100)).'">
<input type="submit" value="submit" name="submit_btn">
</form>';
}
if(isset($_REQUEST['submit_btn']))
{
$user_name= $_POST["user_name"];
$a_random_password = $_POST["a_random_password"];
echo "Your User Name is:". $user_name;
echo "<br> and your Password is : $a_random_password;
}
?>
And my post.php
<?php
$url = "http://test.com/form.php";
$data = array(
'user_name' => 'John',
'a_random_password' => 'xxx',
'submit' => 'submit'
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { echo "Error"; }
var_dump($result);
?>
So how do i get the a_random_password value and submit it along with the form in a single request, else the password wont fit with the user name.
Sup, what you wanna do is impossible using PHP in that way, cause the only job PHP has is to render your content on server side. To listen to the client side you'll need to use javascript.
let randomPassword = document.getElementById('a_randow_password')
let name = document.getElementById('name')
let password = document.getElementById('password')
name.onkeyup = function(){
password.value = randomPassword.value + name.value
}
<input type="text" id="name" name="user_name" placeholder="name"><br />
<input type="hidden" name="a_random_password" id="a_randow_password" value="xxx">
<input type="text" id="password" placeholder="password"><br />
Not sure exactly what you trying to achieve, but if You want to interrupt a request (and modify|use it) from HTML to PHP, You need AJAX request (JavaScript).

Posting JSON data to FOSUserBundle Registration, Login, Profile, etc

I haven't seen any questions about sending requests by JSON to use FOSUserBundle's functions so I am posting this question. I have a Symfony2 project that is primarily designed for mobile use (AJAX too). I am using FOSRestBundle and FOSUserBundle which work well from the forms interface. However, I'd like to be able to register a user for example by posting JSON data to register, login, view profile, etc. How can this be done? Is it even possible to send JSON data to FOSUserBundle? If possible, I'd be glad if you could give an example of how to register or get the profile, etc.
Sample FOSUserBundle login form:
<form action="/projects/symfony/web/app_dev.php/login_check" method="post">
<input type="hidden" name="_csrf_token" value="1cdb2c8fa2fb9a52905ddebff3185ac1a3ad708d" />
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="" required="required" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" required="required" />
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
<label for="remember_me">Remember me</label>
<input type="submit" id="_submit" name="_submit" value="Login" />
</form>
</div>
</body>
</html>
Here is a JSON example - it detects if user is logged in or not
the "code" is the response returned by the action,
the "imageHandler()" is the function that gets triggered using js in this case,for example using intervals or pressing a key.Of course it doesn't need parameters.
the send function is used to send variables to the controller, in this case im using it to send the "imageId" variable with the value given in the parameter(myImageId), same counts for myToDo.
Javascript (This is the twig template)
<script language="JavaScript" type="text/javascript">
function imageHandler(myToDo,myimageId)
{
var xml = ( window.XMLHttpRequest ) ?
new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xml.open("GET", "{{path('imageHandler')}}", true);
xml.setRequestHeader("Content-type", "application/json");
xml.onreadystatechange = function()
{
var serverResponse = JSON.parse(xml.responseText);
if(serverResponse.code == 100 && serverResponse.success)
{
//success
}
else if(serverResponse.code == 200)
{
//not logged in
}
}
xml.send({imageId: myimageId, toDo: myToDo});
}
</script>
/* This is the controller, the javascript knows which controller to call by using the "name annotation"
*/
/**
* #Route(name="imageHandler")
*/
public function imageHandlerAjaxAction(Request $request)
{
//If user is not logged in..
if (false === $this->get('security.context')->isGranted('ROLE_USER'))
{
//return this variables (your choice of course, format: variable=>value)
$response = array("code"=>200,"success"=>false);
return new Response(json_encode($response));
}
}

ajaxForm unable to POST file

What I'm trying to do
I have a form which is posted via ajaxForm. The form contains a file input field, however the data isn't being processed with the rest of the information in the POST.
The code
HTML Form
<form id="profilepicForm" action="user/profilepic.php" method="post" enctype="multipart/form-data">
<input type="file" accept="image/gif, image/jpeg, image/png" name="file" />
<input type="hidden" name="userid" value="<?php echo $_SESSION['user']['id'] ?>" />
<input type="submit" value="Upload">
</form>
Javascript
var options = {
complete: function(response) {
$("#profilepicMessage").html(response.responseText);
},
error: function(){
$("#profilepicMessage").html("ERROR: unable to upload file");
}
};
$("#profilepicForm").ajaxForm(options);
PHP
$user_id = $_POST['userid'];
$image = $_FILES['file']['name'];
print_r($_POST);
exit;
What's happening
All that comes through is Array ( [userid] => 34 ), where 34 is my particular userid. Therefore I know that the form is being posted, but the file is not going through.
You should look at global variable $_FILES.
You'll have to look for something like uploadifive to manage that, for ajax can't currently handle file transfers
(this is not entirely true, there is ajax2 and html5 file api, but save yourself a problem, look for uploadifive).

Form won't POST without Zend_Form

We (the entire team) have been pulling hair over this problem for the last 2 days. For some strange reason our Zend Framework 1.11.2 will not let us post plain form into the controller unless we create a Zend_Form class.
HTML in view file (no javascript, nothing):
<html><body>
<form action="/index/login/" method="post">
Email: <input type="text" name="email"/><br />
Password: <input type="password" name="password" />
<p><input type=submit name="ac" class="btn btn-success" value="Login"></p>
</form></body></html>
Index Controller:
public function loginAction()
{
$request = $this->getRequest();
if ($request->getParam('email')) {
Zend_Debug::dump($request);
}
}
$request->getParams() is empty!
But if we create a Zend_Form or pass the fields in as GET then $request->getParams() is filled with data.
I just don't get it. Is there something in Zend that you have to turn off to use plain form? We think we've tried everything, accessing global $_POST and $_REQUEST variables, and calling $request->getPost(). All empty unless we create a Zend_Form class and instantiate it inside the controller.
Looks like an problem with your Form Action. Please use "baseUrl" View Helper or URL View Helper to create correct action url:
<?php
// correct action url
$actionURL = $this->url(array(
'controller' => 'index',
'action' => 'login',
'module' => 'default',
));
?>
<html>
<body>
<form action="<?php echo $actionURL; ?>" method="post">
Email: <input type="text" name="email"/><br />
Password: <input type="password" name="password" />
<p><input type=submit name="ac" class="btn btn-success" value="Login"></p>
</form>
</body>
...pass the fields in as GET then $request->getParams() is filled with data.
Since you are crafting a form post, you will need to use the getPost() method.
public function loginAction()
{
if ($email = $this->_request->getPost('email')) {
Zend_Debug::dump($email);
}
}
First use the latest version
Zend Framework 1.11.11
Then try this code inside loginAction
if($this->getRequest()->isPost())
{
print_r($this->_getAllParams());
}

Categories