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!
Related
I try to use the update method from bootstrap modal, but when I click edit and url appears in this way http://localhost/../pages/typography#edit?id = 15.
I can not $ _GET ['id']
The error is, the indeterminate index
Try http://localhost/../pages/typography?id=15#edit
The hash part (everything after #) is typically not sent to the server for processing. Anything you want your server to receive needs to be before the # symbol.
This URL http://localhost/../pages/typography#edit?id = 15 ends after #
So, your server gets URI /../pages/typography
The structure or URL is:
protocol://domain_name/URI#anchor
Anchor (after #) can be proceeded on client side with JavaScript.
It seems like the one of the easiest ways to acomplish this is to send an AJAX request to your server using GET. Assuming that your page doesnt change based on the change or sending of the id variable, the following code will work.
Javascript:
xhttp.open("GET", "typography?id=" + id, true);
xhttp.send();
If your page does change by sending the id variable, then your page would have to reload. If that is a no-go you would have to implement a way for the PHP would return a JSON file with the data then your javascript on the gape would have to change the HTML based on the JSON data. This is better long term but is unnecessary to implement for small projects.
I want to extract object values instead of url parameter using PHP.
This is my link http://reussis.com/match-betting/admin2/edit_withdrawal_request.php?id=[object%20Object].
php code
print_r($_GET['id']);
When i print i didn't get any values why?
Is it foolish question please neglect. Thanks!
You cannot pass JavaScript objects directly over HTTP, because HTTP is not JavaScript.
Serialise it by JSON.stringify() on your object, then pass it as an encodeURIComponent()'d URL string.
For example:
let myObject = {'javascript': 1, 'isNumberOne': true};
// Serialises the object into a string, then urlencode it
encodeURIComponent(JSON.stringify(myObject)); // "%7B%22javascript%22%3A1%2C%22isNumberOne%22%3Atrue%7D"
use POST method instead of GET. GET method is an old style and it is prone to the hackers. Try to reconstruct your program now! Good Luck.
Regarding this line:
var data = encodeURIComponent(JSON.stringify(object_literal));
I don't understand why this is being URI encoded.
Later data will be sent via ajax POST.
I understand that URLs, particularly the one you can see in the browser address bar require special characters as described here:
http://www.blooberry.com/indexdot/html/topics/urlencoding.htm
But what exactly does this have to do with Ajax posting?
Do both the url address bar and the internal ajax post utilize the same mechanism?
It all depends on the content type.
Normally when a <form> uses the HTTP method POST then the form values are URL Encoded and placed in the body of the request. The content type header looks like this:
content-type: application/x-www-form-urlencoded
Most AJAX libraries will do this by default since it is universally accepted among web servers. However, there is nothing preventing you from simply serializing the data as JSON or XML and then sending it with a different content type.
content-type: application/json
or
content-type: text/xml
It's worth noting that the payload has nothing to do with AJAX! Under the hood they are all using the XmlHttpRequest object to send an HTTP request asynchronously to the server. It doesn't matter if you send Plain Text, JSON, XML, or even raw binary data so long as you tell the server how to interpret those bits.
The url encoding is purely a historical artifact of how <form> elements posted their data to the server before AJAX was around.
Josh's answer is good, but I think it's missing something. Traditionally form data was posted using the same format as querystrings. eg: param1=value1¶m2=value2 and the only difference between a GET and POST is that POST puts these parameters in the message body whereas a GET puts them in the URL. However, the obvious problem is that if your parameter names or values include unescaped characters like & and =, then you'll screw up the server's ability to automatically parse the parameter collection, resulting in corruption of the data. Using Javascript's encodeURIComponent() function on each parameter value will escape all these characters for you.
So bottom line: if you are not using the old standard parameter collection on the server side--for example, if you are parsing JSON instead--then there's no need to URL encode the text. Also, there's no reason to URL encode if you aren't parsing out multiple parameters on the server side so running encodeURIComponent once on the entire message body makes no sense.
Side note: if you are using asp.net and trying to let users pass html to the server, encodeURIComponent will let you do this without disabling the request validation that normally prohibits this. I don't think sending it as JSON, alone, would accomplish this.
encodeURIComponent is to pass variables over links using GET
JSON.stringify() encodes automatically into utf8
only in some rare cases for example when you want to convert strange charachters to base64 the encodeURIComponent is used outside from GET.
here is an example
base64_encode=function(a){
return window.btoa(unescape(encodeURIComponent(a)));
};
https://developer.mozilla.org/en-US/docs/Web/API/window.btoa
said that ..
if you use a REST API service every ajax GET request which is a string parameter needs to be encoded with encodeURIComponent.
here is an example using yql
https://stackoverflow.com/a/18302867/2450730
No they do not. There is no need for it when it is send as data through Ajax POST.
You can send pure JSON unencoded using AJAX
var ajaxObject = $.ajax({
url: 'url',
type: 'POST',
data: JSON.stringify(object_literal);
});
Here's a stupid question, don't laugh, I've been trying to figure this out but no luck, I guess I'm too tired. So there's an application sending data (image file as string) to a php script, sending it with XMLHttpRequest.send(data). My question is how do I access this string in PHP to save it to a file?
EDIT $_POST, $_GET and $_FILES are all empty
First: Make sure you are sending a POST request (when you call the open method)
Second: Since it looks like you are sending raw data, set an appropriate content type (with setRequestHeader)
Third: You should be able to retrieve the data with $HTTP_RAW_POST_DATA or file_get_contents("php://input");.
I have an interactive web application powered by jQuery where users can manipulate visual objects on the screen. When done, the "state" of JavaScript objects should be sent to PHP to store into database. I'd prefer to use GET for this, but solution that uses POST to submit the data is also viable.
I'm currently thinking to serialize all JS objects using something like base64 encoding and just use something like:
var str = encode_objects();
document.location = 'result.php?result='+str;
However, something tells me there has to be some, more elegant, way than writing my own base64 encoding function in JavaScript. Isn't there something already built into JavaScript that can do the job?
Update: decoding in PHP is not the problem. I know how to decode base64, JSON, whatever in PHP. The problem is how to encode data on JavaScript side.
AJAX is out of the question. It has to be a clean GET or POST with page reload.
json_decode() should serve you well here.
If you simply append a string containing the JSON representation of your javascript object to your HTTP request, you can json_decode() it in PHP and have a PHP object ready to go.
Edit: I should mention that this page has a link to a Javascript JSON stringifier, which will convert your JS objects into the necessary JSON.
first of all, if you're updating the objects state, it should be a POST. try to keep all your GET idempotent.
second, even if you don't want to do any AJAX, JSON is still your friend. the easiest way would be to serialize your objects into JSON and send the resulting string in the POST dataload. there are many ways to decode JSON in PHP, and you're all set.
You can use this serialize function, and then unserialize it on the PHP end.
GET or POST will probably depend on the size of your data : there is a limit on the amout of data you can pass through GET (something like 2000 bytes ; more, depending on the browser).
There is also an other thing to take into account : if you are modifying data, you should use POST ; not GET, which is used to... get... data.
About the format, I would really not go for anything like a custom function doing any kind of stuff like base64 : I would definitly go for JSON, which is a native Javascript notation.
You can for instance have a look at :
wikipedia
http://www.json.org/
There are many JS libraries that can generate JSON (probably every JS Framework can ; and there are standlone libraries like this one) ; and since PHP 5.2 there are functions in PHP to encode/decode it (see json_encode and json_decode)
If it's just a simple flat array you don't need to do anything fancy, as PHP has a built in feature to parse array syntax from GET/POST variable names. Rough example below.
Javascript side:
// Do the parameter-building however you want, I picked the short/messy way
var arrayvalues = [1, 2, 'a'];
var querystring = "var[]=" + arrayvalues.join("&var[]=");
querystring += "&var[something]=abcdef";
// querystring is now "var[]=1&var[]=2&var[]=a&var[something]=abcdef"
PHP side:
var_dump($_POST);
// Remember to validate the data properly!
if ( is_array($_POST['var']) ) {
count($_POST['var']);
echo $_POST['var']['something'];
array_map('do_something_interesting', $_POST['var']);
}
I've used Jquery/JSON.
var jsonArray = $.toJSON(jsArray);
Then sent it via JQuery/Ajax