If I want to put a value between single quotes in Javascript how can I sanitize/encode it so that any quotes in the value doesn't cause issues?
I also want to then use this value in a query string which I will then be passing to PHP.
Whatever is used I need to be able to decode it back to it's normal value with PHP.
Example:
$foo = "Hey, what's up!?"; // PHP
getGrades('<?=$foo?>'); // JS Function
function getGrades(var) {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'grade=' + var;
// Run the AJAX request
runAjax(loadUrl, dataString);
}
function runAjax(loadUrl, dataString) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
someFunction(response);
}
});
}
// get_grades.php file
$grade = $_GET['grade']; // We now want this value to be it's normal value of "Hey, what's up!?";
getGrades('<?=$foo?>'); // JS Function
json_encode will make a string JavaScript safe (and quote it).
getGrades(<?php echo json_encode($foo); ?>);
I also want to then use this value in a query string which I will then be passing to PHP.
Pass data: an object, not a string. jQuery will handle the escaping for you.
var dataString = { grade: var }; // Rename the variable too
If you have concatenating with single quoted string it will not be an issue. Only thing left is when you use it in query string. In that case You should use encodeURIComponent.
Also change your var to something else. var is a keyword in JavaScript.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With