The problem is that angularjs sends post data as json. There are several solutions:
Serverside:
Angularjs - Form Post Data Not Posted?
Clientside:
http://sebgoo.blogspot.de/2013/05/angularjs-post-data-to-php.html
More fancy one?:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
I want to use the server side one:
PHP file:
<?php
$data = file_get_contents("php://input");
$errors['EncodeI']=$data->customerFirstName;
$data = json_decode($data, TRUE);
$errors['EncodeII']=$data['customerFirstName'];
echo return_sql2json($errors, $rows);//just a function which returns the error messages
?>
Js:
...
$http({
url: 'read.php',
method: "POST",
// headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
params: {
customerFirstName: $scope.customerFirstName,
customerLastName: $scope.customerLastName,
customerEmail: $scope.customerEmail
}
}).success(function(data) {
....
My Header: The data customerFirstName is sent
Remote Address:::1:80
Request URL:http://localhost/360/app/read.php?customerEmail=aa&customerFirstName=aa&customerLastName=aa
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:0
Cookie:AccessKey=somePW; Email=someemail; PHPSESSID=somesession
Host:localhost
Origin:http://localhost
Pragma:no-cache
Referer:http://localhost/360/app/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
Query String Parametersview sourceview URL encoded
customerEmail:aa
customerFirstName:aa
customerLastName:aa
Response Headersview source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:Keep-Alive
Content-Length:310
Content-Type:text/html
Date:Wed, 07 May 2014 11:21:46 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive:timeout=5, max=96
Pragma:no-cache
Server:Apache/2.4.9 (Win32) OpenSSL/0.9.8y PHP/5.4.27
X-Powered-By:PHP/5.4.27
And the Response:
errors: {EncodeI:null, EncodeII:null, customerFirstName:First Name is required,…}
EncodeI: null
EncodeII: null
customerEmail: "Email is required"
customerFirstName: "First Name is required"
customerLastName: "Last Name is required"
success: false
Conclusion: Not working. Also the server side solutions I didn't manage to be successful but they anyways look more complicated for me.
The answer is rename params into data.
Related
I am working on this prototype and i have used the php built in web server, and all works perfect except handling a range request from Safari for a mp4 file. i have the following bootstrap code that gets executed for every incoming request for the php built in server
$extensions = array("html");
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$ext = pathinfo($path, PATHINFO_EXTENSION);
if (!in_array($ext, $extensions)) {
return isRangeRequest();
}
require_once(__DIR__ . $path);
function isRangeRequest()
{
$filelength = filesize(__DIR__ . '/video/video.mp4');
if (isset($_SERVER['HTTP_RANGE'])) {
$ranges = explode(',', substr($_SERVER['HTTP_RANGE'], 6));
$parts = explode('-', $ranges[0]);
$start = $parts[0]; // If this is empty, this should be 0.
$end = $parts[1]; // If this is empty or greater than than filelength - 1, this should be filelength - 1.
if (intval($end) == 0) return false;
$readBytes = $end - $start + 1;
header('HTTP/1.1 206 Partial Content');
header("Content-Length: " . $readBytes);
header('Content-Type: video/mp4');
header('Content-Range: bytes '.$start.'-'.$end.'/'.$filelength);
ini_set('memory_limit', "512M");
$fp = fopen(__DIR__ . '/video/video.mp4', 'rb');
if ($readBytes < 4096) {
print(fread($fp, $readBytes));
flush();
} else {
fpassthru($fp);
}
fclose($fp);
exit;
}
return false;
}
i have verified using tcpdump that the code above sends all the correct headers and i manage to get safari to start playing the video. however safari only is able to play the first few frames and then video stops.
here is response headers from a nginx server for the same request from safari
GET /video/video.mp4 HTTP/1.1
Host: job.local
Accept-Language: en-us
X-Playback-Session-Id: CD33782F-F257-4506-95C4-94ABD4E200CE
Cookie: PHPSESSID2=avrunqgk9rkb3941fe24q9asd6
Range: bytes=0-1
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://job.local/test.html
Accept-Encoding: identity
Connection: keep-alive
HTTP/1.1 206 Partial Content
Server: nginx/1.6.2 (Ubuntu)
Date: Fri, 27 May 2016 03:29:16 GMT
Content-Type: video/mp4
Content-Length: 2
Last-Modified: Thu, 26 May 2016 17:53:49 GMT
Connection: keep-alive
ETag: "5747382d-8c6c509"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Content-Range: bytes 0-1/147244297
GET /video/video.mp4 HTTP/1.1
Host: job.local
Accept-Language: en-us
X-Playback-Session-Id: CD33782F-F257-4506-95C4-94ABD4E200CE
Cookie: PHPSESSID2=avrunqgk9rkb3941fe24q9asd6
Range: bytes=0-147244296
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://job.local/test.html
Accept-Encoding: identity
Connection: keep-alive
HTTP/1.1 206 Partial Content
Server: nginx/1.6.2 (Ubuntu)
Date: Fri, 27 May 2016 03:29:16 GMT
Content-Type: video/mp4
Content-Length: 147244297
Last-Modified: Thu, 26 May 2016 17:53:49 GMT
Connection: keep-alive
ETag: "5747382d-8c6c509"
Expires: Thu, 31 Dec 2037 23:55:55 GMT
Cache-Control: max-age=315360000
Content-Range: bytes 0-147244296/147244297
and here is the headers from the php built in server using the bootstrap code above
GET /video/video.mp4 HTTP/1.1
Host: localhost:8005
Accept-Language: en-us
X-Playback-Session-Id: 740A36CB-C116-4F5E-A3BD-5B4B3A27B543
Range: bytes=0-1
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://localhost:8005/index.html
Accept-Encoding: identity
Connection: keep-alive
HTTP/1.1 206 Partial Content
Host: localhost:8005
Connection: close
X-Powered-By: PHP/5.5.30
Content-Length: 2
Content-Type: video/mp4
Content-Range: bytes 0-1/147244297
GET /video/video.mp4 HTTP/1.1
Host: localhost:8005
Accept-Language: en-us
X-Playback-Session-Id: 740A36CB-C116-4F5E-A3BD-5B4B3A27B543
Range: bytes=0-147244296
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4
Referer: http://localhost:8005/index.html
Accept-Encoding: identity
Connection: keep-alive
HTTP/1.1 206 Partial Content
Host: localhost:8005
Connection: close
X-Powered-By: PHP/5.5.30
Content-Length: 147244297
Content-Type: video/mp4
Content-Range: bytes 0-147244296/147244297
apart from Connection: keep-alive not being supported by the built-in php server i don't see any other difference in the response. Do you see any potential issues here? The mp4 files is about 100MB and if i use a data-url instead of a file reference would that be ok?
This project is for a prototype that used only on a local machine, so there is no performance or security concerns and please avoid making such comments. the core concern is the reason why safari only plays the first few frames. (i also observed if the range request is not handled correctly safari will not even play the first few frames. So there is some other issue that maybe not so obvious.
Im struggling with sending JSON data via XMLhttp post request.
Data is:
"{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"
JS code is:
var reqData = {
reqType : "post", //isDateRequested : 1,
reqName : "getCurrTemp",
reqPayload : ""
};
var dataToSend = {'reqData' : reqData };
var jData = JSON.stringify(dataToSend);
alert(jData);
var oReq = new XMLHttpRequest();
oReq.onload = function() {
data = JSON.parse(this.responseText);
};
oReq.open("POST", "handleRequests.php", true);
oReq.send(jData);
Im having problem on php side, looks like server does not recognize JSON, or even message lost...
I used wireshark to sniff traffic:
POST /autHouse/handleRequests.php HTTP/1.1
Host: 192.168.0.12
Connection: keep-alive
Content-Length: 70
Origin: http://192.168.0.12
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Content-Type: text/plain;charset=UTF-8
Accept: */*
Referer: http://192.168.0.12/autHouse/ah.html
Accept-Encoding: gzip, deflate
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}HTTP/1.1 200 OK
Date: Tue, 19 Jan 2016 10:53:22 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.45-0+deb7u2
Content-Length: 84
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: text/html
string(70) "{"reqData":{"reqType":"post","reqName":"getCurrTemp","reqPayload":""}}"
here is php code:
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData'], true);
$reqType = $reqData["reqType"];
$reqName = $reqData["reqName"];
and realted php error log:
[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] , referer: http://192.168.0.12/autHouse/ah.html
[Tue Jan 19 11:54:23 2016] [error] [client 192.168.0.121] PHP Notice: Undefined index: reqData in /var/www/autHouse/handleRequests.php on line 15, referer: http://192.168.0.12/autHouse/ah.html
Can you please tell me why php complians while im sending proper JSON data?
regards
J.
Try this
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "handleRequests.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(jData);
You have missed a level in the resulting array.
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData'], true);
$reqType = $reqData['reqData']["reqType"];
$reqName = $reqData['reqData']["reqName"];
If you prefer using the objects that the data is being passed as rather than converting the objects to arrays you can do
$body = file_get_contents('php://input');
error_log(var_dump($body));
$reqData= json_decode($_POST['reqData']);
$reqType = $reqData->reqData->reqType;
$reqName = $reqData->reqData->reqName;
Scenario: Playing an online game, have an javascript file that allows me to port data to a PHP on a server using POST/json. I have to enter the path of my server into my client PC for this to work. I am getting a confirmation that connection is fine.
The PHP only recognises source from the website I am playing on, and I can see data transferring to the site in my developer console. The data being POSTed is in the following format:
I can see the data coming in an array looking at the console:
Request URL: //xxxxxx.xxxx/aix/server_api.php Request Method:POST Status Code:200 OK Request Headersview source Accept:application/json, text/javascript, */*; q=0.01 Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-GB,en-US;q=0.8,en;q=0.6 Connection:keep-alive Content-Length:65236 Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Host:sd.fast-page.org Origin:http://xx.yyy.com Referer:http://xxx.yyy.com/232/index.aspx User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Ubuntu Chromium/25.0.1364.160 Chrome/25.0.1364.160 Safari/537.22 Form Dataview sourceview URL encoded alliance[id]:118 alliance[name]:DS alliance[members]:12 alliance[score]:982078 data_type:city data[0][id]:12517457 data[0][owner_id]:1538 data[0][owner]:MM1 data[0][coords]:'081:191 data[0][name]:C31 4Chief data[0][score]:11020 data[0][city_type]:castle data[0][location]:land data[1][id]:12517458 data[1][owner_id]:1538 data[1][owner]:MM1 data[1][coords]:'082:191 data[1][name]:C31 5Redrum data[1][score]:10596 data[1][city_type]:castle data[1][location]:water data[2][id]:12386381 data[2][owner_id]:1538 data[2][owner]:MM1 data[2][coords]:'077:189 data[2][name]:C31 1Home data[2][score]:10460 data[2][city_type]:castle data[2][location]:land data[3][id]:12320847 data[3][owner_id]:1538 data[3][owner]:MM1 data[3][coords]:'079:188 data[3][name]:C31 6North data[3][score]:10182 data[3][city_type]:castle data[3][location]:land data[4][id]:12386382 data[4][owner_id]:1538 data[4][owner]:MM1 data[4][coords]:'078:189 data[4][name]:C31 3Back data[4][score]:10108 data[4][city_type]:castle data[4][location]:land data[5][id]:12517453 data[5][owner_id]:1538 data[5][owner]:MM1 data[5][coords]:'077:191 data[5][name]:C31 2Second data[5][score]:9968 data[5][city_type]:castle data[5][location]:land data[6][id]:12714060 data[6][owner_id]:1538 data[6][owner]:MM1 data[6][coords]:'076:194 data[6][name]:C31 MacoHub data[6][score]:9692 data[6][city_type]:castle data[6][location]:land data[7][id]:12517460 data[7][owner_id]:1538 data[7][owner]:MM1 data[7][coords]:'084:191 data[7][name]:C31 Tango data[7][score]:9163 data[7][city_type]:castle data[7][location]:land data[8][id]:12582993 data[8][owner_id]:1538 data[8][owner]:MM1 data[8][coords]:'081:192 data[8][name]:C31 Spring data[8][score]:8864 data[8][city_type]:castle data[8][location]:land data[9][id]:12517454 data[9][owner_id]:1538 data[9][owner]:MM1 data[9][coords]:'078:191 data[9][name]:C31 Pally data[9][score]:8816 data[9][city_type]:castle data[9][location]:land data[10][id]:12779603 data[10][owner_id]:1538
[and so on and so forth.....have masked the rest but this is the format
Response Headersview source Access-Control-Allow-Headers:Content-Type Access-Control-Allow-Methods:POST, GET, OPTIONS Access-Control-Allow-Origin: //xxx.yyy Access-Control-Max-Age:1000 Cache-Control:no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform Connection:keep-alive Content-Encoding:gzip Content-Length:70 Content-Type:application/json Date:Fri, 29 Mar 2013 18:08:14 GMT Expires:Fri, 29 Mar 2013 18:08:14 GMT Pragma:no-cache Server:Apache Vary:Accept-Encoding X-Powered-By:PHP/5.5.0alpha5
Now what I see above is the output to the console on my PC when I trigger the client app.
The PHP is as follows:
$m = false;
if(preg_match('/http\:\/\/game url/',$_SERVER['HTTP_ORIGIN'],$m))
{ $m = $m[1]; }
if(empty($m)) { die('Invalid Origin.'); }
if(!empty($_POST['data_type']))
{
$sender = $_POST['sender'];
$alliance = $_POST['alliance'];
$request = $_POST['data_type'];
$data = $_POST['data'];
// Response to Alliance Info Exporter
$json = array(
'message' => 'recieved.',
'data' => array(),
'error' => false
);
// handle data types
switch($request)
{
case 'connection_test': $json['message'] = 'Welcome to our server. Your are connected!'; break;
case 'member' : /* Code for member request */ break;
case 'city' : /* Code for city request */ break;
case 'support' : /* Code for support request */ break;
default : $json['message'] = 'Nothing Done.'; break;
}
// set headers for API
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-type: application/json');
// Respond
die(json_encode($json));
}
die('No Access.');
I have two or three problems here
I can't seem to manipulate the data that the PHP is getting at all
Whenever I try to add any arguments to the case statement just to even see if I can parse the data somehow then the api stops responding to my client
For example, at the city switch I just tried to output the data to a file just to confirm it was coming through because my browser console gives me a POST success code (http 200)
This is the code I used:
$f = fopen("city.txt", "w");
fwrite($f, $_POST);
fclose($f);
I tried it in the main part of my PHP, tried it at the city case switch (that is the type of query I am executing first), and I tried with other defined types like $data, etc. Nothing writes.
What am I doing wrong?
Secondly my endstate is to post this to a SQL server, how would I do that?
I am developing a single page script i.e. category.php for category management.
This script have an input button to invoke AJAX call.
<input type="button" id="btn" />
Jquery code to bind click event and call ajax. I want json response.
$(document).ready(function(e) {
$('#btn').click(function(e) {
id=1;
jQuery.ajax({
type: 'post',
url: 'category.php',
success: function(data) {
if(data.rstatus==1){
alert(data.text);
}else
alert(data);
},
data:{'id':id}
});
});
});
A php code to entertain AJAX call.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']);
header("Content-type: application/json");
json_encode($jsonResponse);
die();
}
Problem:
This ajax call is unable to produce correct response in call back function, and cause error in firebug console.
TypeError: data is null
In FIREBUG Headers are as follow:
Response Headers
> Cache-Control no-cache, must-revalidate Connection Keep-Alive
> Content-Length 0 Content-Type application/json Date Tue, 26 Mar 2013
> 12:45:52 GMT Expires Mon, 26 Jul 1997 05:00:00 GMT
> Keep-Alive timeout=5, max=98 Last-Modified Tue, 26 Mar 2013
> 12:45:52GMT Pragma no-cache Server Apache/2.4.3 (Win32) OpenSSL/1.0.1c
> PHP/5.4.7 X-Powered-By PHP/5.4.7
Request Headers
> > Accept */* Accept-Encoding gzip, deflate
> > Accept-Language en-US,en;q=0.5 Content-Length 4
> > Content-Type application/x-www-form-urlencoded; charset=UTF-8
> > Cookie __gads=ID=39701a3d85dce702:T=1350383638:S=ALNI_MY_rHGVQ-qNxH4UGmbY_G-IuVcDkA;
> > __utma=141011373.593047819.1350426838.1364292528.1364295112.314;PHPSESSID=1s73cho6ildjt80jtudt8nq0f5 Host abc.com Referer http://www.abc.com/category.php
> > User-Agent Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101
> > Firefox/19.0 X-Requested-With XMLHttpRequest
It's look like your response content is empty. You forgot an echo.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']);
header("Content-type: application/json");
echo json_encode($jsonResponse);
die();
}
If you want to response a json, you must put it in the response content. In Php, you just have to use echo to put something in the response content.
This doesn't work simply because $_SERVER doesn't contain that information. All request headers aren't really stored there. Have a look at getallheaders (http://php.net/manual/en/function.getallheaders.php)
Edit: Oh, also you need to echo the response. $_SERVER may contain the information you need in this case, but it is not reliable and portable. I'd still advise you to use getallheaders
don't use HTTP_X_REQUESTED_WITH - barely works in jQuery
try to send additional var, like
data:{'id':id, 'request':'xmlhttprequest'}
In Safari and Firefox, the response part of the code is not working (i.e. from PHP-->Ajax-->jQuery). The variables definitely make it to the PHP fine (tested using mail() ), so it's probably some small error on my behalf!
jQuery:
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: "http://www.kudiclub.com/test/login/?loginsub",
success: function(data){
if(data.success==false){
$("#login .error").html(data.reply).show();
$("#login-email").val(data.email);
$("#password").val("");
}else{
window.location = data.ref;
}
}
});
PHP:
$data = array('success' => false, 'reply' => 'Username and password did not match.', 'email' => $email);
print json_encode($data);
return;
Hoping somebody can help. Thanks, Nick.
SOLUTION
After much fiddling about, it turns out that it doesn't see a full URL as a relative path. Changing the url to '/test/login/?loginsub' did the trick.
The server says: Content-Type: text/html. Is not a json document (application/json).
http://www.kudiclub.com/test/login/?loginsub
GET /test/login/?loginsub HTTP/1.1
Host: www.kudiclub.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Cookie: PHPSESSID=060b8210adfb3c67ff792b9471c7fa1c
Cache-Control: max-age=0
HTTP/1.1 200 OK
Date: Thu, 02 Aug 2012 22:12:10 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html