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.
Related
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;
}
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.
I need to get javascript variable value in php file.
html example:
UPDATE:
$html = '
<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
Shout I use regex ? regex is very complex to me... any help ?
<?php
$html = '<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
$variables = ["adminSeq", "companyId"];
$counter = 0;
foreach($variables as $variable) {
preg_match_all('/"(.*?)"/', $html, $matches);
${"$variable"} = ($matches[1])[$counter];
$counter++;
}
echo $adminSeq; // Prints out: 3423423423423
echo $companyId; // Prints out: 2349093284234
?>
You can also use GET requests to do this. The link would look like http://localhost/?adminSeq=3423423423423&companyId=2349093284234 then get out these values in PHP with:
<?php
$adminSeq = $_GET["adminSeq"];
$companyId = $_GET["companyId"];
?>
My index.php page includes a config.php file, which returns an array that I have defined some variables in by using "define('var1' , 10)".
I am trying to validate my forms input, but I can't figure out how I can reference var1 from within the JS function. What is the easiest way to do this?
Just echo it to a javascript variable:
<script type="text/javascript">
var var1JS = "<?php echo $var1; ?>";
</script>
Not quite sure I am full understanding without seeing the code but, you could echo the variable from the PHP array in the JS function (as above answer).
Or Echo the entire JS query:
$y = count($PHPdata_array);
echo "function exampleFunction() {";
echo "var ArrayName = [";
for ($i = 1; $i <= $y; $i+=2) {
echo "{" . $PHPdata_array[$i] . "," . $PHPdata_array[$i-1] . "},";
}
echo "];";
i have the following code, but it will not work. i am trying to create a script output:
echo "<script type=\"text/javascript\"><!--\n";
echo "SLIDES = new slideshow(\"SLIDES\")\n";
// Now loop through the files, echoing out a new select option for each one
foreach( $files as $fname ) {
echo 's = new slide()\n';
echo 's.src = \"http://cashbackflorida.com/wpradmin/modules/wprrets/photos/'.$result ->MLS.'/'{$fname}\n\"';
echo 's.width = \"560\"\n';
echo 's.height = \"420\"\n';
echo 's.alt = \"{$fname}\"\n';
echo 's.text = unescape(\"\")\n';
echo 's.link = \"\"\n';
echo 's.target = \"\"\n';
echo 's.attr = \"\"\n';
echo 's.filter = \"\"\n';
echo 'SLIDES.add_slide(s)\n';
}
echo '--></script>\n';
Don't do it this way. Just output the array to JavaScript and deal with it there.
var files = <?php echo json_encode($files); ?>;
You'll find the problem in your string escaping
echo 's.height = \"420\"\n';
You can't escape in single quote strings like that. So try this
echo "s.height = \"420\"\n";
You do NOT need to escape single quotes within double quotes or visa versa, but you can only get a newline character like that in a double quote string.
I would recommend HEREDOC for this kind of string writing though.
$fnamej = json_encode($fname);
echo << EOT
s.height = "420";
s.alt = $fnamej;
EOT;
I am also inclined to say that you'd be better off handling this in javascript. This may end up behaving very badly all of a sudden, and it will take up more bandwidth.