How can i add two variables between single quotes - javascript

I have
function delImage(posteId,imagebinId) {
$.get("<?php echo base_url('/Home/deletePostimage/') ?>");
return false;
}
i want to be like /Home/deletePostimage/posteId/imagebinId
i tried
$.get("<?php echo base_url('/Home/deletePostimage/')+posteId+"/"+imagebinId ?>");
but it divide the two numbers
like posteId=5 imagebinId =2
the results will be
/Home/deletePostimage/2,5
the params from
<a class="postimgsd" onClick="if(confirm('Are you sure you want to delete this image ?')){delImage(<?php echo $value['id'],$get_images[0]['binId']; ?>); rmItem(<?php echo $i; ?>);}else{} ; " >

With ES6, you can do this with string interpolation:
$.get(`<?php echo base_url('/Home/deletePostimage/${postId}/${imagebinId}') ?>`);
Without ES6, there is another answer that answers it, or use this:
var url = '/Home/deletePostimage/' + postId + '/' + imagebinId;
$.get("<?php echo base_url('" + url + "') ?>");
Furthermore, the code that calls this function should actually be:
<a class="postimgsd" onClick="checkDeletion()" />
<script type='text/javascript'>
function checkDeletion() {
if(confirm('Are you sure you want to delete this image ?')) {
var postId = <?php echo $value['id']; ?>;
var imagebinId = <?php echo $get_images[0]['binId']; ?>;
delImage(postId, imagebinId);
rmItem(<?php echo $i; ?>);
}
}
</script>

You need to keep in mind that PHP is processed on back-end before send the html to your user browser. That said, everything between php tags (<?php ... ?>) is rendered/processed before javascript even exists.
So if you put any JavaScript code inside your PHP code it won't work.
To make it work and be clean, do something like this:
function delImage(posteId,imagebinId) {
let url = "<?php echo base_url('/Home/deletePostimage/') ?>";
$.get(url + posteId + "," + imagebinId);
return false;
}

Related

how to pass php variable to javascript?

I am using following code to pass PHP variables to javascript. but it is not working.
function gto(str) {
document.getElementById('goto').action = str;
document.getElementById('ID').value = <?php echo "$userid" ?>;
document.getElementById('name').value = <?php echo "$user_name" ?>;
document.getElementById('gname').value = <?php echo "$usergname" ?>;
document.getElementById('fmname').value = <?php echo "$userfname" ?>;
document.getElementById('img').value = <?php echo "$userimg" ?>;
document.getElementById('email').value = <?php echo "$useremail" ?>;
document.getElementById('goto').submit();
}
Following is the PHP code
<?php
if($_POST["name"] == null)
{
$user_name = 'Annomyous';
}
else{
$user_name = $_POST["name"];
$userid= $_POST["id"];
$usergname= $_POST["gname"];
$userfname= $_POST["fname"];
$userimg= $_POST["img"];
$useremail= $_POST["email"];
}
echo "<p style='color : white'>$user_name";
echo "$userid" ;
echo "$gname";
echo "$fname";
echo "$img";
echo "$email";
echo "$user_name";
echo "$user_name</p>";
$user_name =htmlspecialchars($user_name);
$user_name =str_replace("<script>","", $user_name);
?>
the output is a follows:
ReAlItY TuTs104598758504708047866ReAlItY TuTsReAlItY TuTs//this is php echo output.
JAVASCRIPT OUTPUT:-
function gto(str) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = ;
document.getElementById('name').value = Annomyous;
document.getElementById('gname').value = ;
document.getElementById('fmname').value = ;
document.getElementById('img').value = ;
document.getElementById('email').value = ;
document.getElementById('goto').submit();
}
Function gto is called here:
<button class="w3-btn header-btn" onclick="gto('Contact.php');">Contact Us</button>
I can see in PHP output I am getting all variable output.
but nin juavascript im getting only Annonymous why????
I need to pass post variables to contact us so i am using the form tag and javascript but this is not working Please help me!
Thanks in Advance
values from php to js can be passed in many ways, here's one of them
try to pass the php values when calling the js function, like this:-
<button onclick="gto('Contact.php','<?php echo $userid;?>','<?php echo $username;?>');">Contact Us</button>
and then get values on js function like this:-
function gto(str,userid,username) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = userid;
document.getElementById('name').value =username;
}
that's it, now use the values in js as your wish
Uh, found another issue. The js is in smart quotes, which won't work... "`" is invalid. use "'".
Also, w3schools can't handle php in their editor, so it's no use.
Example for POST requests: https://www.w3schools.com/code/tryit.asp?filename=FQSA8MJYGJ47
Hope this helps.

Javascript not able to print large string

I am entirely new to JavaScript and the only reason I need it now is to update a picture on a PHP page. The picture is in Base64. This is the code I currently have:
if($data != null){
$data = "data:image/jpeg;base64, " . $data;
?>
<script type="text/javascript">
var myvar = "<?php echo ($data); ?>";
document.write("test" + myvar);
</script>
This simply does not output anything.
However, if I try something like this:
if($data != null){
$data = "data:image/jpeg;base64, " . $data;
?>
<script type="text/javascript">
document.write("test" + "<?php echo strlen($data); ?>");
</script>
it does work and outputs a number somewhere between 10.000 and 20.000. I read on the internet that there is not really a max variable size in JavaScript, atleast not one I am able to reach with this size.
What am I doing wrong?

Assigning PHP Variables To Javascript Variables Not Working

I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.

How to retrieve $_SESSION value in a JavaScript/HTML

I have this working script yet when I change it to retrieve(supposedly) the value inside $_SESSION["username"], it doesn't retrieve anything. The whole page is saved as .php as I am using some codes that uses PHP.
Code:
echo "<script type=text/javascript>";
echo "var hidden = false;";
echo "function actiondb1() {";
echo "if(!hidden) {";
echo "document.getElementById(\'clickdb1\').style.visibility = \'hidden\';";
echo "document.getElementById(\'db1\').style.visibility = \'visible\';";
echo "document.getElementById(\'db1\').disabled = false;";
echo "document.getElementById(\'db1\').value =".$_SESSION["username"];.";";
echo "}";
echo "}";
echo "</script>";
How can I make the script to properly retrieve the data inside $_SESSION["username"];?
Observe that, for instance, if the value of $_SESSION["username"] is John, your echo will be generating this result:
document.getElementById('db1').value = John;
But John is supposed to be a string and should be wrapped in quotation marks, otherwise JavaScript will understand it as a variable name (which value will be probably undefined).
As Havenard mentioned, this line is missing Javascript single quotes to properly denote a string variable:
echo "document.getElementById(\'db1\').value ='".$_SESSION["username"];."';";
However, you really shouldn't print JS out with PHP if you can help it. Though iatboy's answer answer won't ultimately fix your bug, it is a much cleaner way of doing things.
?>
<script type=text/javascript>;
var hidden = false;
function actiondb1() {
if(!hidden) {
document.getElementById('clickdb1').style.visibility = 'hidden';
document.getElementById('db1').style.visibility = 'visible';
document.getElementById('db1').disabled = false;
document.getElementById('db1').value ='<?php echo $_SESSION["username"];?>';
}
}
</script>;
<?php
Did you start session in this page?If you didn't,use the follow code to start session.
session_start();
Then change your code to
echo "<script type=text/javascript>";
echo "var hidden = false;\n";
echo "function actiondb1() {\n";
echo "alert('".$_SESSION['username']."')\n"; //test code
echo "if(!hidden) {\n";
echo "document.getElementById('clickdb1').style.visibility = 'hidden';\n";
echo "document.getElementById('db1').style.visibility = 'visible';\n";
echo "document.getElementById('db1').disabled = false;\n";
echo "document.getElementById('db1').value ='".$_SESSION["username"]."';\n";
echo "}\n";
echo "}\n";
echo "</script>";
it will be ok.

.replace() not working inside a jQuery function

I don't understand why replace() function doesn't work into my jQuery function:
jQuery(document).ready(function($){
var amount_min = <?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>;
var amount_min = amount_min.replace(/[^\d]/g, "");
$('input[name=amount]').val(amount_min);
});
Whatever input I give (for example "100ab" or "10.000") it doesn't replace it with "100" or "10000".
How to do?
You forgot to put double-quotes.
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo 0; ?>";
Because, replace works in Strings.
UPDATE #1
If for any religious reason you don't want to wrap the PHP in double quotes then output them along with the number.
var amount_min = <?php echo '"' . ($_GET['amount_min'] ? $_GET['amount_min'] : 0) . '"'; ?>;
UPDATE #2
Compulsory validation you can use:
var amount_min = <?php echo '"' . (int)($_GET['amount_min']) . '"'; ?>;
can you please try this:
$(document).ready(function(){
var amount_min = "<?php if($_GET['amount_min']){ echo $_GET['amount_min'];}else{ echo '0';} ?>";
console.log("original-> "+amount_min);
var amount_min = amount_min.replace(/\D/g,'');
console.log("replaced-> "+amount_min);
});
Your PHP code is outputting a number:
var amount_min = 100;
Since you're expecting a string, wrap it in quotes:
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>";
I haven't touched PHP in years, but I think you could simplify your code a little:
var amount_min = "<?php echo($_GET['amount_min'] || '0'); ?>";
Also, why don't you just fetch the GET parameter with JavaScript?
You don't need the .replace() code (it also only works on strings); PHP can already do the proper conversion for you:
$(function() {
var amount_min = <?php echo isset($_GET['amount_min']) ? (int)$_GET['amount_min'] : 0; ?>;
$('input[name=amount]').val(amount_min);
});
You could also use filtering for this:
<?php echo filter_input(INPUT_GET, 'amount_min', FILTER_VALIDATE_INT, array('options' => array('default' => 0))); ?>
Note that filter_input would not accept a value like 100abc, so use wisely.
If you still want to use strings safely in JavaScript you should use json_encode().
Btw, any answer that involves an unmodified echo of a request variable from PHP inside JavaScript code is wrong and can cause XSS attacks! You have been warned.
Update
The regular expression based replacement can also be done in PHP:
var amount_min = <?php echo (int)preg_replace('/\D+/', '', isset($_GET['amount_min']) ? $_GET['amount_min'] : 0); ?>;
Since all non-digits are removed, you can safely apply the (int) cast.

Categories

Resources