Saving text with an hash mark (Javascript - PHP - MySQL) - javascript

I am writing simple AJAX functions to send comments to the server and save them in a mySQL database with php.
The following code seemed to work just fine for my purposes, basic but did his job, until i tried to put a hash symbol (#) in a comment.
Inserting this into the text "crashes" my functions, without saving the written text in the database and returning an empty div basically.
This is the ajax call:
function sendComment(n){
var xmlhttp = createAjax();
var text = document.getElementById("f"+n).value;
if (!validation(text))
return false;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
appendComment(n, xmlhttp.responseText);
}
}
...
url = "comments.php?news="+n+"&text="+text;
xmlhttp.open("GET", url, true);
xmlhttp.send();
...
}
Where createAjax simply creates the xmlhttp object for every browser as standard, validation is a function that checks for many symbols like <,>,=,(,),| with a regular expression.
this is the php part:
function insertComment($text, $news){
$conn = dbConnect();
$user = $_SESSION["user"];
$text = nl2br(htmlentities($text));
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO comments(user, news, date, text) VALUES ('".$user."','".$news."','".$date."', '".$text."')";
mysql_query($sql) or die ("Errore in inserimento: ".sql_error());
echo writeSingleComment($user, $date, $text);
mysql_close(conn);
}
It just connects, saves the comment and returns the html code with echo, so that the javascript function can print it.
This works with any text apparently, but I can't get it to work with an hash, am I missing something?
Sidenotes, I could simply add the symbol to the validation regular expr., but my point is to "print" it, not just excluding it. Thanks in advance!
Sidenote 2, the javascript attaches the comment to a static element.

url = "comments.php?news="+n+"&text="+text;
You aren't escaping any of the data you are putting into your URL.
Some characters have special meaning, e.g. & separates query parts and # starts the fragment identifier.
You need to run your input through encodeURIComponent() before adding it to the URL.
url = "comments.php?news=" + encodeURIComponent(n) + "&text=" + encodeURIComponent(text);

Many characters (such as #) are not SQL safe and require escaping
At the very least you need to use
var toSend = escape(mystring);
this will not protect from attacks but will get you down the road.

Related

Not sure how to use PHP function in HTML file that leverages JS variables from that HTML file

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

Getting data in JavaScript from php

Specifically, I need to get data in html from a database. If there is a simple way to do that in JavaScript then just skip the next part ^^
I have successfully written the php code to retrieve the data from the database, which is something like this:
$host = (host)
$user = (user)
$db = (database)
$pw = (password)
$funct = $_GET["Function"];
switch ($funct) {
case "getName": {
$personid=$_GET["PersonID"];
$output = getName($host, $user, $pw, $db, $personid);
echo $output;
break;
}
}
Of course there are more values for $funct, but to keep things short I only wrote one and left out the function itself. I tested it by making a form with method="GET", and it correctly prints the name. So my actual question is how to pass the name onto a html document, where I want to list the names of certain people. I did research and found for example that I need to use "echo $output;", I had originally tried "return $output;" but that was not enough. My current js-code is something like this:
"use strict";
function getName(field_id, person_id) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("name"+field_id).innerHTML=this.responseText;
}
};
request.open("GET", "people.php");
request.setRequestHeader("Function", "getName");
request.setRequestHeader("PersonID", person_id);
request.send();
}
I originally tried fetch(), because it was recommended by javascript.info, but I didn't find many examples, so I scratched that. If i change it to ".innerHTML=this.responseText+this.status;" it just prints "200" onto the name field. There are no error messages.
It probably looks like I'm making it too complicated, but the code is supposed to do more stuff than what I shared, I'm just keeping it simple for you to understand.
I hope you can help me!
$_GET won’t give you the request headers, it will give query string parameters. You want to change your request to request.open("GET", "people.php?Function=getName&PersonId=" + person_id).

What is the right way to send a password through JavaScript AJAX to PHP?

I have tried a few methods, I have confirmed that it's a special character problem ie. I tried a simple password combination that only included letters/numbers and that worked.
Since I stopped using jQuery this is the first time I've had a problem where password_verify would not work. I did make sure as I mentioned above it wasn't anything wrong with password_verify.
So I get my password input and I join it with the username like this:
var params = null,
paramObj = {};
paramObj['user'] = loginInpUser.value;
paramObj['pass'] = loginInpPass.value;
params = encodeURI('post_params='+JSON.stringify(paramObj));
On the PHP side I receive this in POST like so:
$post_params = json_decode($_POST['post_params'], true);
$user = $post_params['user'];
$pass = $post_params['pass'];
I did make sure I get matching values from what I send on the client side, to what PHP gets ie. echo out $user and $pass, they match exactly... the special characters in question are:
)(#$$%)(
I haven't even tried to throw in a & in there which may cause problems with how you concatenate the parameters before sending them with an XMLHttpRequest.
So what is the right way to do this where special characters are still parsed correctly (password_verify matches hash with password)?
There is a reason to not use jQuery for me it was to lower file download speed-use async tags.
Edit:
Weird thing with hashes:
I just needed a basic login system so I didn't bother with a register form, I created a hashing function that used password_hash and inserted it into a db. I noticed that using
$pass = "password with special chars";
Would fail, the error would say that something inside the string was an undefined variable (string is cut up, I guess a parsing error).
But using
$pass = 'password with special chars';
This was fine.
You should either send the entire request as JSON, or URL-encoded; a mix of both is rather weird:
var params = 'user=' + encodeURIComponent(loginInpUser.value) + '&pass=' + encodeURIComponent(loginInpPass.value);
$user = $_POST['user'];
$pass = $_POST['pass'];
Or:
var params = JSON.stringify({ user: loginInpUser.value, pass: loginInpPass.value })
$params = json_decode(file_get_contents('php://input'), true);
echo $params['user'], $params['pass'];
This properly preserves arbitrary "special" characters correctly.

Array not passing with ajax.

This is the java script code for ajax call. In this case code variable get a c program code and pass it to the compiler.php page.
function insert(){
var code = document.getElementById("file_cont").value;
var arr = new Array(code,"c");
alert(arr[0]);
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//window.location.assign("login.php");
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST","server_controlers/compiler.php?q="+JSON.stringify(arr),true);
xmlhttp.send();
}
Ajax call work well but the case is in php file. I'm decode the jason array to $arr variable. But if i echo like this echo $arr[0] it is empty. But if i not include the code to the array in the java script like this var arr = new Array("aaaa","c"); its works fine. Can some tell me what is the wrong when i send the array with code variable. This is the php file.
<?php
if(isset($_REQUEST["q"])){
$arr = $_REQUEST["q"];
$arr2 = json_decode($arr);
echo $arr2[0];
/*$file = fopen("../temp_files/c/mmm.c","w");
fwrite($file,"$arr[0]");
fclose($file);
shell_exec('gcc -ommm ../temp_files/c/mmm.c');
system('mmm', $retval);*/
}else{
}
?>
server_controlers/compiler.php?q="+JSON.stringify(arr)
Your data is not being made URL safe. You say that it contains c code, this means it might include (for instance) the & character which would break the query string format and cause the JSON to be invalid when extracted from it.
You need to run the data through encodeURIComponent before putting it into your URL.
server_controlers/compiler.php?q=" + encodeURIComponent(JSON.stringify(arr))
I think the problem in ur request type POST/GET. U shuffled 2 request types in 1. Also how i can see u try to send get request? but in parameters u use type POST.
All information what u need about GET request u can find here.
Also u can try change ur php code too. If u need to use POST
<?php
if($_POST){
print($_POST);
}
?>
After u can do all u need with data array.

How to read the post request parameters using JavaScript

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

Categories