Getting POST data using AltoRouter PHP - php

I've implemented Alto Router in my MVC framework and it's routing Get requests using the URI perfectly.
It's got to the point where i need to start dealing with forms and POST data, so ive set up a route to deal with a POST request, the request works and i get taken to the post requests route e.g domain.com/contact/send/
Unfortunately i don't get the POST data in the params array on the match.
I'm not sure if im getting myself confused as to whether the router should do this or not.
If the router is not supposed to handle getting the POST data, could you point me in the right direction of how i could ideally handle the POST data?
If the router is supposed to handle POST data, home comes i can't see it in the params array of the match?
Here's a snippet of the POST request:
$router->map('POST','/contact/send/,'contact#send', 'contact_form_send');
$match = $router->match()
Any help will be much appreciated, thanks

Here is how I do it.
$router->map('POST', '/companies/create', function() {
if isset($_POST['company'])) {
createCompany($_POST['company']);
}
});
hope it helps

If you take a look at the AltoRouter source, params is extracted from the request URL, so it will not contain any POST data. This parameter is mainly used by AltoRouter for its reversed routing feature, but you can use it instead of accessing $_GET directly.
If you need to access POST data you will have to get it from the request directly by using either the $_POST or $_REQUEST superglobal.
Note that AltoRouter will overwrite $_REQUEST when you call match so it may behave differently than expected since it will not contain cookies.

I get POST data through php://input
// update a document
$router->map('POST', '/docs', function () {
$rc = new DocumentController();
$data = json_decode(file_get_contents('php://input'));
$data = (array)$data;
$rc->updateDocument($data);
});

Related

Angular http.get/post with URL in data being passed

I have the following http.get request...
$http.get("api/checkSave/"+ JSON.stringify($scope.programDetails)).then(function(data) {
....
});
In my programDetails object, there is at least one field that can have a URL in it. I thought the stringify would've properly encoded the object so it would get passed correctly to my PHP function. What seems to happen though is that the URL isn't sent properly. I get an error that the server responded with a 404 not found error. I manually tried removing the URL in the request (copied it to the browser and sent an empty string for the URL field) and the request was processed correctly - that's why I am thinking the stringify can't do what I need.
I also need to send this data via a http.post later to save the data in the object. Hopefully, whatever I need to do in the get will also apply when I call the post.
Should the stringify pass along the data correctly or do I need to encode it differently? I've been using stringify in other apps, but haven't had to pass a URL in the data.
If I need to do it differently, I would need to know what to do on the PHP side to decode it for processing. The examples I find for get/post all seem to pass individual variables and not an object and not with an URL in one of the variables. I've seen encodeURIComponent mentioned but wasn't sure if that's what I need to use instead and if so, then what to use on the PHP side to decode it properly.
This doesn't really have much to do with the data consisting of a URL (only that a URL has a much better chance of having characters in it that have special meaning within a URL than other data).
The problem is that you are putting the data into a URL and URLs are not JSON texts.
To encode a string to put it in a URL use encodeURIComponent.
So it ended up that I had to replace the '/' in the fields that contained links and then it worked. Otherwise, the '/' was making it seem as though I was passing additional parameters in my get call. Thanks for the help!

jQuery AJAX not sending to my PHP program

I'm no expert in AJAX (or jQuery) but I thought what I was doing was pretty easy yet when I send an ajax request with:
$.ajax ( requestObj );
it doesn't send and I'm hoping someone can help. In order to give context, I've set the "requestObj" up as follows:
//initialise a request object
var requestObj = {};
requestObj.response = 'ajax-response';
requestObj.type = 'POST';
requestObj.url = my_config['ajax-service-list'][service]['url'];
requestObj.data = $.extend ( requestObj.data , {
action: service,
other: parameters,
_ajax_nonce: my_config['ajax-service-list'][service]['nonce']
});
requestObj.global = false;
requestObj.timeout = 30000;
requestObj.success = function ( r ) {
alert ( "Success: " + r );
}
requestObj.error = function ( r ) {
console.log ("FAILURE WITH AJAX Call ( " + JSON.stringify (r) + ")");
}
There's one thing that probably needs explaining. The two references to "my_config" are references to a Javascript variable that I set using Wordpress's wp_localize_script() function. Basically it just provides context about where to find the URL, the NONCE to use, etc. I have tested that the URL and NONCE information is working correctly so that shouldn't be the problem. For example, I put a breakpoint on the browsers debugger on the line after the two references are defined and got these results:
When I call the ajax function it immediately executes the success function and sends in the value of 0. Looking at my PHP error logs though I can see that the request was never sent. What could be getting in the way of $.ajax(requestOb) from actually sending the request?
UPDATE:
Thanks to Michael's sage advice I realised that I am in fact getting a request to go out but as it's running in a local environment the response is coming back lightening fast. Now I am suspecting this has more to with Wordpress configuration. I have hooked into the wp_ajax_[service_name] but it immediately returns 0. I'll re-ask this question with this new information in the wordpress forum.
You should be using a browser inspector to detect if an ajax request is made. Open up the network tab of any inspector, and you can watch requests as they happen. How is the $.ajax() method being instantiated? You may have an issue with that, as opposed to $.ajax().
Once you've used the inspector, look at the $_POST or $_GET data you're sending in the headers section, and then look at the response. Is the HTTP response code 200? If it's 500, then you probably have an error in your PHP controller that receives the request.
If you have PHP CLI, run this to see if you have a syntax error:
php -l path/to/php/controller.php
If you have a non-fatal error in your file, you'll see the error output in the request response.
Try var_dump( $_REQUEST ) at the top of your php file, too, to make sure that the file is receiving the data, and you can inspect it inside the browser-inspector response.
If you have a problem with the program inside of your controller... you've got yourself a new question to post. :)
At first look, it looks like your URL has spaces around get_action_template. That might be an issue.
Also, passing dataType might help.
If not try getting a JSON response without any parameters and post the output
Ok, i've answered this damn question finally. Arrgh. BIG, BIG THANKS to Mathew to who's troubleshooting skills I could not have done without. Anyway, the problem was in the AJAX request and as a result the Wordpress Ajax manager was never respecting the "hooks" I had put into place on the PHP side.
How was my AJAX request off? I had a POST request but the URL had GET variables hanging off of it. The key variable for Wordpress based Ajax requests is the "action" variable. This is the variable which WP's ajax manager uses to distinguish the various services and is the name that you'll be hooking into.
So in the end, my URL was:
http://mysite.com/wp-admin/admin-ajax.php
and my POST variables included:
action: get-action-template
My wordpress hook is:
add_action ( 'wp_ajax_get-action-template' , 'AjaxServiceManager::ajax_handler' );
My sleepless nights may continue but they won't be related to this damn problem anymore. :^)

Check and send variables via URL without redirection

i am trying from my main web page to check and in some cases send a variable via URL like this (http://192.168.0.110/CVAL.CGI?A0=1) this is to modify the status of something in my web page depending on the value seen in the url.
Sounds like you need Ajax.
There are many javascript libraries that can help you with this functionality such as jQuery, Prototype, or one of the many found on this page.
Hope that is what you are looking for and is helpful. Next time post more specific details so we can answer your question correctly the first time. Specific, detailed examples of what you want to do are also helpful.
UPDATED:
Here is an example using the Prototype Javascript library given your example form:
new Ajax.Request('/CVAL.CGI?A0=1', {
method: 'get',
parameters: { anotherValue: 'something' },
onSuccess: function(transport) {
alert(transport.responseText); // this is what the server returned
}
});
This would result in a request to /CVAL.CGI?A0=1&anotherValue=something. Whatever CVAL.CGI returns in response to that request, is available from transport.responseText.
This way, the user never has to leave the page or submit a form but it is all done behind the scenes. Your parameters can be any values you want to send which you can grab from form fields or other user input. You can return responses in JSON to make accessing the return data easier as well. Change method from 'get' to 'post' to do post requests.

what's the best way to post 30 variables from client side to server?

hey,
i have about 30 variables which are created and modified by user (none of which comes from input, so submitting a form is not really an option), once modification finished a JS function process the variables and spouse to post them to the controller which will then send the to the model.
now, as appears in the title, my question is what is the best way for me to send them?
thnx for time and attention,
Ido
I wouldn't use GET for this unless it's something like a complex search form.
You can POST values in JavaScript either by using some form of AJAX or by generating a hidden form and submitting it.
Modern browsers and newer versions of PHP both support JSON, and there are supporting libraries you can use if the browsers you need to support or the PHP version you're stuck with are old. I'd recommend this as a way of getting data back and forth.
Client side JS:
var myobject = {
userparam: "value",
anotherThing: "another value",
something: "etc"
}
var serialized = JSON.stringify(myobject);
// use any AJAX technicque to POST 'serialized' back to the server
Then on the server-side:
<?php
$myobject = json_decode( $_POST['serialized'], true );
$myobject['userparam'] == "value"; // true
Hope this helps!
I would use a POST using an ajax-submitted form. You can simply create a form with hidden inputs and then use your favorite ajax library to submit the form to the server as a POST request.
If the variables are tightly related you can shove them into an array and POST them (use Javascript to construct the array of course). Another alternative would be to name each one of them and POST them separately?
POST array look like this: arr[]=Hello&arr[]=World
in PHP you can access it like
<?php
arr = $_POST['arr'] // ["Hello", "World"]
?>
Hope that helped!
Weigh it up between POST and GET. GET is better if you want to navigate back to the a page with a given set of 'variables'. POST is better if you're submitting a lot of content. However, a POST request is less 'efficient' as a GET request - bear that in mind and only use POST if you really need to.

Can user send HTTP_RAW_POST_DATA to my site?

A stupid question but I am a little confused.
I use pubsubhubbub and check for a new information with if(isset($_HTTP_RAW_POST_DATA)).
I check if user is logged with:
if(isset($_SESSION['user'])) {
//logged
}
Can a user send a HTTP_RAW_POST_DATA?
So, basically anyone who sends an HTTP POST request to your callback will actually send a $HTTP_RAW_POST_DATA. Many languages and framework have libraries to parse this into HTTP POST params.
In the context of PubSubHubbub, the body is NOT made of params, so you have to use the lower level $HTTP_RAW_POST_DATA, as parsing the XML as params would not make any sense.
If you're trying to secure your callback URL, there are multiples ways to do it:
Make your callback URLs unique and un-guessable : for example, use a unique internal identifier in the URLs for each feed to which you subscribed.
Subscribe using http*s*, and by providing a hub.secret. This secret will then be used by the hub to compute a unique signature for each notification. You have to make sure this signature matches the content that you get. Read more about this here.
The raw post data is the data that is used to extract the POST parameters that can be accessed by $_POST. An user can also post un-parametarized data with post, yes.
A user will always send raw POST data to your scripts. PHP will then parse it and populate $_POST. When POSTing from a form, $_POST is equivalent to:
parse_str($HTTP_RAW_POST_DATA, $data);
var_dump($_POST);
var_dump($data); // yields the same as $_POST
However, if you really want to fetch the raw POST data, the preferred way is:
$rawPost = file_get_contents('php://input');
... because $HTTP_RAW_POST_DATA relies on the always_populate_raw_post_data INI setting, and also because it won't work with multipart/form-data content type.

Categories