I have an index HTML page that grabs a user's username and password from a form.
I want to base 64 encode this before passing it to a php file that makes a request to a server with the encoded credentials.
I tried doing something like:
<script>
// The below function calls the PHP file responsible for retrieving campaign details.
function getCampaignDetails() {
var username = $('#username').val(); //This successfully returns the username.
var password = $('#password').val(); //This successfully returns the password.
var authentication_string = <?php $username = urldecode($_GET['username']); $password = urldecode($_GET['password']); echo base64_encode($username.':'.$password); ?>;
$.ajax({
type: "GET",
url: "http://localhost/testing/get_campaign_details.php",
headers: { 'Access-Control-Allow-Origin': '*' },
data: {
"authentication_string": authentication_string
},
});
}
</script>
But I get an error about an unexpected token < which I'm assuming is a syntax error in the authentication_string value. If I add quotes around this value, the php doesn't execute and I get the whole string as is passed to the php file, rather than the encoded credentials.
Is there a way to use PHP in a basic HTML file that grabs a JavaScript variable value, uses a PHP function to get a new value, and then pass back this new value to the data in an Ajax request from the HTML file that is then subsequently utilized by another PHP file?
Or is there a way to base 64 encode something using an HTML/JavaScript function instead of PHP function?
Best,
You need to add quotation marks around the php that you're running to get the authentication_string.
var authentication_string = "<?php $username = urldecode($_GET['username']); $password = urldecode($_GET['password']); echo base64_encode($username.':'.$password); ?>";
Javascript is expecting a value that it can assign to the variable authentication_string after the = like an int or a string. When it see's < it doesn't know what to do with it so it throws an unexpected token error.
As a sidenote - passing a username and password in the querystring (the url) is not a good idea. Even though they are encoded it's better to keep those kind of things away from prying eyes. There's a post here that might be helpful on how to handle sensitive data like that. Best way to pass a password via GET or POST
I'm trying to create a js that send data to a php.
My first problem is that I get get back a html code if I insert this to the php.
This is only for understand the idea. So the js should send the "param" to the php and the php should return the result6 variable in this case, but I get a html code...
$('#f_field').change (function()
{
var param = 28;
$.post('check_mutet.php', param, function(result6) {
alert(result6);
});
});
while check_mutet.php contains this
<?php
$result6=666;
echo $result6;
Thank you for your help, as you can see I'm rather noob :)
param is a plain string (it starts out as a number, but will be converted to a string by the time it gets through to HTTP).
This will be available as STDIN in PHP, which you can read as described in answers to this question.
However, you should encode the data into a structured format that is easier to use.
The traditional format for this is application/x-www-form-urlencoded, which is the default format sent by HTML forms.
If you pass an object to jQuery post, it will encode the data in that format for you:
var param = 28;
var data = { example: param };
$.post('check_mutet.php', data, function(result6) {
Then you can read it through the POST superglobal in PHP:
<?php
$result = $_POST['example'];
I have problem with send array in $.post to php.
var_dump result is "NULL"
JSON.stringify doesn't work..
JQUERY
var photobox = [];
photobox.push(e.target.result);
$.post("../modules/upload.php",{"images[]" : photobox, count : sum},
function(data)
{
$('.list').prepend(data);
}).done(function() {
$('#files').prop('disabled', false);
$('.file-search').html("Szukaj...");
$(".img-thumbnail").removeClass("first");
$(".img-thumbnail").first().addClass("first");
e.target.result is base64 code
PHP
$images = $_POST['images'];
var_dump($images);
You can send arrays like this:
$.post('/thepage.php', {'NameOfKey': variableName});
The above code will allow VariableName to be an Array.
You would need to encode to JSON on your client, but when on your server (PHP) convert it back to an array by using json_decode:
http://php.net/manual/en/function.json-decode.php
I have a problem with sending an object in PHP. I stringify the object before sending it to the PHP file.
The PHP file then uses json_decode. But the decode shows a blank variable.
The object which i console.log shows this as its structure:
Its then sent to PHP with this :
console.log(my_Obj);
var as = JSON.stringify(my_Obj);
call_data('add.php?&as='+as, nxtFunc);
Now in the PHP file i have this which handles the situation:
$path = json_decode($_GET['as']);
echo $_GET['as'].'<br/>';
print_r($path);
die;
The result is:
[null,null,{\"8\":[null,null,null,null,null,null,[],[],[],[],[]],\"9\":
[null,null,null,null,null,null,null,null,null,null,[]],\"10\":
[null,null,null,null,null,null,null,null,null,null,[],[]],\"11\":
[null,null,null,null,null,null,null,null,null,null,null,[]]}]
<br/>
My XHR request url in Chrome shows:
add.php?as=[null,null,{%228%22:[null,null,null,null,null,null,[],[],[],[],[]],%229%22:[null,null,null,null,null,null,null,null,null,null,[]],%2210%22:[null,null,null,null,null,null,null,null,null,null,[],[]],%2211%22:[null,null,null,null,null,null,null,null,null,null,null,[]]}]
Notice the print_r shows nothing. Should i not be using stringify ?
Thats because my_Obj is an array and not an object.
Try this:
var as = JSON.stringify({data: my_Obj});
Note:
You will also need to clean up the array before stringifying - i.e. clear out all null/undefined indices. Check this answer: https://stackoverflow.com/a/281335/921204
I am trying to save some data on the server but finding some encoding problems.
This is how I am sending my objects to PHP (which works fine but I don't think the contentType is actually doing anything):
$.post(
'myfile.php',
{
contentType: "application/x-www-form-urlencoded;charset=utf-8",
data : myData
},
function (data, textStatus, jqXHR){
//some code here
}
);
and then in PHP (myfile.php):
<?php
header('Content-Type: text/html; charset=utf-8');
$file = 'data/theData.txt'; //the file to edit
$current = file_get_contents($file); // Open the file to get existing content
$a2 = json_decode( $current, true );
$data = $_POST['data']; //the data from the webpage
$res = array_merge_recursive( $data, $a2 );
$resJson = json_encode( $res );
// Write the contents back to the file
file_put_contents($file, $resJson);
?>
As you can see I am getting the original contents of the file and decoding the json. I am then merging the result with the data sent from the webpage before re-encoding in json and put the contents back.
This all works as expected. However, at one point in my Jquery the data sent contains a wide variety of symbols like "/ ö é ł Ż ę"
When the file is saved each '/' has an escape character '\' in front of it and likewise the 'é' for example is '\u00e9'
How do I override this? Should I try to convert it properly in the PHP or is their a way in the JQuery to convert back to the correct format after I have $.get('data/theData.txt'?
Any light shed on this issue is greatly appreciated! Please excuse the poor variable names.
The link provided by #chalet16 helped but if JSON_UNESCAPED_UNICODE doesn't work for you this does the job!
$myString = $json_encode($myObject);
//After initially encoding to json there are escapes on all '/' and characters like ö é ł Ż ę
//First unescape slashes:
$myString = str_replace("\/","/",$myString);
//Then escape double quotes
$myString = str_replace('"','\\"',$myString);
//And Finally:
$myNewString = json_decode('"'.$myString.'"');
If you are using PHP >=5.4.0, you can use JSON_UNESCAPED_UNICODE option in json_encode function. Please look at php.net: json_encode for more details.
For PHP < 5.4.0, there are some comments about how to do this in user contributed notes on the same page, but it is uncertain that it will work correctly or not.