I am new to AngularJs. I was trying to create a simple application using angularjs.
In a simple application i am not able to print posted data via $_POST, $_GET or$_REQUESTin my php script.
While usingfile_get_contents("php://input")` i am able to print data.
Can any one let me know why $_GET, $_POST and $_REQUEST are not working?
My Index.html Code :
<!DOCTYPE html>
<html ng-app>
<head>
<title>Search form with AngualrJS</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="http://code.angularjs.org/angular-1.0.0.min.js"></script>
<script src="search.js"></script>
</head>
<body>
<div ng-controller="SearchCtrl">
<form class="well form-search">
<label>Search:</label>
<input type="text" ng-model="test" class="" placeholder="Keywords...">
<button type="submit" class="btn" ng-click="search()">Search</button>
<p class="help-block">Try for example: "php" or "angularjs" or "asdfg"</p>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
</body>
</html>
search.js code :
function SearchCtrl($scope, $http) {
$scope.url = 'search.php'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.search = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
$http.post($scope.url, { "data" : $scope.test}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
Search.php Code :
<?php
// The request is a JSON request.
// We must read the input.
// $_POST or $_GET will not work!
$data = file_get_contents("php://input");
$objData = json_decode($data);
// perform query or whatever you wish, sample:
/*
$query = 'SELECT * FROM
tbl_content
WHERE
title="'. $objData->data .'"';
*/
// Static array for this demo
$values = array('php', 'web', 'angularjs', 'js');
// Check if the keywords are in our array
if(in_array($objData->data, $values)) {
echo 'I have found what you\'re looking for!';
}
else {
echo 'Sorry, no match!';
}
Any assistance will be appreciated.
To go along with my comment about a possibility of a bad setting in php.ini, this article(dead link) (linked through this one, from my comment) also offered this quote:
If the Content-Type is empty or not recognized in the HTTP message then the PHP $_POST array is empty. Not sure if this is a bug or is by design…
The symptoms being the same, (empty $_POST but data available through php://input), this brings up the number of possible reasons this error is occurring to two:
Syntax error in php.ini post_max_size setting
Bad value or empty Content-Type header being sent from the front-end
If your setting for post_max_size is correct, then it could be that angular is removing the Content-Type header for the post. According to this question and this question, angular will remove the Content-Type header if there is no payload or an empty payload going along with any request, which I believe is your issue.
Try adding this in your SearchCtrl:
function SearchCtrl($scope, $http) {
$scope.url = 'search.php'; // The url of our search
$scope.test = {test:'test'}; // Add me
// ...
I suspect your $_POST array will become filled, since there will now be a Content-Type header being sent along with the request, and actual request data being sent. If that works, it means that your test input isn't binding correctly to the scope, or you're submitting empty data. Try adding a guard clause before the HTTP Request:
if($scope.test) {
$http.post($scope.url, { "data" : $scope.test})
// ...
Related
I am using angular http client to interact with database and everything works but when I am trying to POST data to the same link using a form, I get that the data is undefined.
I was trying to encode, decode values as I know that before making any POST request and sending data, I need to perform angular.toJSON method, but that did not work.
This is my index.php where I receive a POST request from the form.
if (empty($action)) {
if ((($_SERVER['REQUEST_METHOD'] == 'POST')) &&
(strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false)) {
$input = json_decode(file_get_contents('php://input'), true);
$action = isset($input['action']) ? $input['action'] : null;
$subject = isset($input['subject']) ? $input['subject'] : null;
$data = isset($input['data']) ? $input['data'] : null;
}
case 'createNote':
// if I die() here, it prints the die()
if(!empty($data)) {
// if I die() here, $data is undefined.
$data = json_decode($data);
$user = $data[0];
$comment = $data[1];
$film_id = $data[2];
$lastupdated = date("Y-m-d H:i:s");
$sql = "INSERT INTO nfc_note (user, film_id, comment, lastupdated)
VALUES (:user, :film_id, :comment, :lastupdated)";
}
break;
My form that I use to send POST request
<form action="index.php" method="POST">
<input type="hidden" name="action" value="create">
<input type="hidden" name="subject" value="note">
<input type="hidden" name="data" value="<?php echo "['username','content', 1]"; ?>">
<input type="submit" value="Submit">
</form>
As mentioned above, it works when I use angular's http and pass parameters like this:
this.createNote = function (data) {
var defer = $q.defer(),
data = {
action: "create",
subject: "note",
data: angular.toJson(data)
};
$http
.post(urlBase, data)
.success(function (response) {
defer.resolve({
data: response.data
});
})
.error(function (error) {
defer.reject(error);
});
return defer.promise;
};
Does not work when I use a form. Any suggestions or mistakes that I am not aware of?
Your PHP code is expecting Json formatted data, and it is not getting that. It is because the HTML Form sends out POST data as application/x-www-form-urlencoded.
To support both data formats, you need to build a logic on your PHP code to detect either format. The data format is mentioned in the HTTP header where you can check that. Look for Content-Type. For POST data coming for your HTML form, it is application/x-www-form-urlencoded and for the Json it should be application/json.
You can read the form values in PHP by using $_POST[<form_parameter>]. In your case $_POST['data']. To make your HTML form a bit simpler you can also split the data array into their own inputs in the form.
See this for some more info: https://www.smtpeter.com/en/documentation/json-vs-post
I had the problem something like
"POST request to PHP does not retrieve any data when using a form instead of angular http client".
Normally use stream php to detect data from Angular to PHP
$data = file_get_contents('php://input');
But when scan the code with fortify it detect the xss vulnerability and I must change the methods.
Solved this problem in this way, I hope that help someone. :-)
ANGULAR:
$http({
method: 'POST',
url: '<?php echo base_url(); ?>admin/saveTemplateEmail',
headers: {'Content-Type': 'application/json'},
data: {templateEmail:$scope.selectedTipology}}).then(function (response) {.....}
PHP:
$data = file_get_contents('php://input');
$post_val = json_decode($data, true);
I changed it to the following
ANGULAR:
$http({
method: 'POST',
url: '<?php echo base_url(); ?>admin/saveTemplateEmail',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
data: jQuery.param({templateEmail:$scope.selectedTipology})}).then(function (response) {.....}
PHP:
$post_val = $_POST;
I am trying to make a post request from my angular js, as below
var postData={
firstName:'VenuGopal',
lastName:'Kakkula'
};
postData=JSON.stringify(postData);
$http({method:'POST',url:'http://localhost/blog/posttest.php?insert=true',data:postData,headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function (data,status,headers,config) {
alert('Success' + data);
})
.error(function (data, status,headers,config) {
// uh oh
alert('error' + status + data);
});
I am not sure how to read this POST DATA in my PHP REST webservice.
<?php
header("Access-Control-Allow-Origin:*");
header('Access-Control-Allow-Headers:Content-Type');
header("Content-Type:application/json");
if(!empty($_GET['insert']))
{
$result=json_decode($_POST['firstName']);
deliver_response(200,"Got the Post data","GotData $result");
}
function deliver_response($status,$statusmsg,$data)
{
header("HTTP/1.1 $status $statusmsg");
$response['status']=$status;
$response['status_message']=$statusmsg;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
I tried the below options
json_decode($_POST['firstName'])
json_decode($_POST['data'])
json_decode($_POST['[postData'])
None of them returned the data, Its always returning the error Undefined index: firstName in F:\xampp\htdocs\Blog\posttest.php on line 10
Can anybody help me how I can read the POST request data sent in php file.
Most likely it is because you are submitting JSON data which is not automagically populated into the $_POST variable per standard form data.
The work around is to manually parse the input into a variable for use.
Example:
<?php
$args = json_decode(file_get_contents("php://input"));
echo $args->firstName;
?>
You can also solve this problem without changing code in server and use $_POST the regular way. Explained here: http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
I have a nginx rewrite rule that redirects an img src attribute to a php page. Within this php page I'm trying make a GET request, which on success makes a POST request to the same page, sending the data returned from the GET request as the data. Why is the $_POST data empty in the php script? If I hardcode $name = "http://path/to/my/img.png" in the php script the image renders correctly.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
var_dump($_REQUEST);
//if(isset($_POST['val'])) {
// open the file in a binary mode
$name = $_POST['val']; // ALWAYS EMPTY
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
//echo fpassthru($fp);
header("Location: $name");
exit;
//}
?>
<html>
<head>
<script type='text/javascript' src='/steal/steal.js'></script>
<script type="text/javascript" src="/plugins/jquery/json2.js"></script>
<script type="text/javascript">
steal('jquery/dom/fixture').then(function(){
$.fixture("GET /event/{code}", function(original, settings, headers){
return [200, "success", { "img_url":"http://path/to/my/img.png" }, {} ]
})
var strObj = <?php echo json_encode($_REQUEST); ?>;
var str = strObj.q;
var eventCode = str.split('/')[1];
$.ajax({
url: "/event/"+eventCode,
success: function(data) {
var imgUrl = data.img_url
$.ajax({
type: 'POST',
contentType: 'json',
data: {val:imgUrl},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
}
});
}
});
});
</script>
</head>
<body>
</body>
</html>
Alright, you've taken things a few steps beyond what is possible.
When the user hits this image in their email, a request is sent to your server asking for that image. None of that javascript is going to make it back to the user because the <img> tag is expecting an image, not an html document. You can tack things on to the outgoing request via something like
<img src="http://yourwebsite.com/tracker.php?val=someimage.png">
and your script will be able to get val out of $_GET but you won't be able to make a POST request for this image from inside an email.
All that $_REQUEST data you're getting at the top there? That's where you get all your email tracking data from. Everything you can get out of there and $_GET is all you're getting.
Afterwards, you need to give them back an image. So heres how you do that.
$val = $_GET['val']; // assuming val contains an image
header('Content-Type: image/png');
readfile('/path/to/your/images/'. $val);
Please be super aware that you need to sanity check $val to make sure its only containing images that you want to be able to see. A potentially malicious user could see this and put something like tracker.php?val=/etc/passwd or something similar and then you've got PHP trying to read your password file. Making sure that images exist and can even be read can be done with the is_readable() function.
I am doing a simple ajax request to another domain like this:
<script type="text/javascript">
$(function() {
$('.clik').click(function() {
$.ajax({
type: "POST",
url: "http://sub.mydomain.com/test.php",
crossDomain: true,
dataType:"jsonp",
success: function(data) {
$('p.txt').html(data['no']);
}
});
});
});
</script>
</head>
<body>
<p class="clik">Halleluja</p>
<p class="txt"></p>
this is the test.php page on sub.mydomain.com
<?
header('Access-Control-Allow-Origin: http://mydomain.com');
// Begin Session
require_once('cl.session.php');
$session = new Session();
$session->start_session('test', false);
// Access Database
require_once('cl.database.php');
$login_db = new Database('user', 'pass', 'accounts', 'test');
$login_pdo = $login_db->PDO;
include "fn.check_login.php";
if(checkLogin($login_pdo) == true) {
// We start out by checking if the request has been made using AJAX
if (is_ajax()) {
echo "this is working";
} else {
echo "this is not working!";
}
} else {
echo 'You are not authorized to access this page, please login. <br/>';
}
// Function to check if the request is an AJAX request
function is_ajax() {
// BOOLEAN return if AJAX
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
It returns a semantic issue.
Also if I simply echo some basic text:
<?
echo "Hello World!";
?>
it still returns a semantic issue.
could somebody tell me what went wrong?
Well, for a start, JSONP requests can't be POST (only GET). But I tend to assume jQuery is ignoring the invalid type. JSONP is intrinsically a GET.
Your response to it is invalid. You've told jQuery you're expecting the server to provide a JSONP response. but your responses aren't JSONP.
A JSONP response would look something like this:
callback({
"property": "value",
"anotherProperty": 42
})
...where the name of the callback (callback in the above) is taken from the query string of the request. So for instance, if the request were http://sub.mydomain.com/test.php?callback=foo, the response would use foo for the name of the callback:
foo({
"property": "value",
"anotherProperty": 42
})
jQuery will add the callback= query string parameter to the request for you automatically, and generate the corresponding function for you, which in turn calls the ajax success handler with the data passed into it.
I think you may need to use the jquery postMessage plugin (or similar if there is one). Long time since I tried it but check if you load the script from the server you wish to call (think I tried that and failed in the past but hey - its worth a bash - report back if it does).
I have a simple sign up mailing list form. It sends the user's email address to a store-address.php file. I use jQuery's ajax object to send a request to the php file and then receive a response.
The problem is I am not getting a response from the php file. I tried setting the cache to false in the request. I also tried send the information through the URL like so:
http://www.fifthtribe.com/inc/store-address.php?ajax=true&cache=false&email=test4%40gmail.com
When I do it that way it works and gives me a reponse. But when I do it through ajax it doesn't give me a response. This is from Firebug:
And here's snippets from my code:
HTML:
<div id="mlist">
<form id="mlist_form" method="POST" action="">
<input type="text" id="email" name="email" placeholder="Email" />
<input type="submit" id="submit_btn" value="Join" />
</form>
<div id="response"></div>
</div>
JQuery:
/* Add to mailing list */
$("#mlist_form").submit( function(e){
//$('#response').append('<div id="thanks-mce"><div id="mce-arrow"></div>Thanks for signing up!</div>');
var email = escape( $('#email').val() );
e.preventDefault();
data = {
"ajax" : "true",
"email" : email,
"cache" : "false"
}
$.ajax({
type: "POST",
url: 'inc/store-address.php',
data: data,
success: function( msg ){
// successfully signed up
$('#response').html( msg );
$('#email').val('');
},
error: function( err ){
// error while signing up
$('#response').html('Error: Is your email correct?');
}
});
return false;
});
PHP:
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us4');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "xxxxxxxx";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
You realize that your PHP script is using GET method but your jQuery code is using the POST method right?
If the information is being posted to PHP, PHP will need to use $_POST to retrieve it. This explains why the URL method using $_GET works but the jQuery POST doesn't.
Good luck!
It looks like you're using $_GET instead of $_POST. Try echoing out the contents of $_REQUEST to see what that holds.
Debug your script!
Place an alert in the success and error parts of your script and then you will know whether the AJAX is working.
If not, you can then work your way up the document and see where the problem is.
In addition, the error here is quite simple. You are using $_GET in PHP and you are POSTING your data using AJAX, this will not show an error. Although the PHP document will not process your request because it is not being fed any parameters.