Writing HTML code in Javascript inside a PHP code - javascript

I need to write in PHP, inside a Javascript portion code, an hidden input tag with an javascript array that I need to pass to another PHP code ..
This is the sample code ...
echo '<script type="text/javascript">';
<other javascript code .... >
echo 'arr_selections_json = JSON.stringify(arr_selections);';
echo 'document.write("<input type="hidden" name="arr_selections_json" value="+arr_selections_json+" />")';
This code doesn't work .... Any suggestions?
Thank you in advance .. .

You need to JS-escape the double quotes inside the argument of document.write()
e.g.
echo 'document.write("<input type=\\"hidden\\" name=\\"arr_selections_json" value=\\"" + arr_selections_json + "\\" />")';
Also, I've had recent weird cases, where document.write wouldn't consider the closing slash (/>), whereas it's HTML-5 compliant. I had to escape with a backslash the closing slash.

What about this ?
<script type="text/javascript">;
<other javascript code .... >
arr_selections_json = <?php echo JSON.stringify(arr_selections); ?>;
document.write('<input type="hidden" name="+arr_selections_json+" value="+arr_selections_json+" />');
</script>
I'm not sure what are your php part, but i think you should be ok like this.

Related

including html tag in a php code, specifically dealing with href function inside a php block

enter the html code once a condition is satisfied but then i aim to use php values and html tags together.
tried tag etc and got most of the part in running just unable to deal with href beacuse it is referencing to some values.
not sure where to use "" or ``.
<?php.....
echo `Yes`;
?>
"yes" should work as a hyperlink but at the moment the php values are not processed that`s why no result.
You are using wrong sequence of quote
<?php
...
?>
<?php
echo '<a href="limitdatabase.php?Dropdown=' .
$_GET['Dropdown'].
';&search='.
$search_name .
';&wise='.
$_GET['wise'].
';">Yes</a>';
?>
and you should use single quote and not backtics for string
You are using incorrect concatenation. Whenever you want to add any PHP variable then you need to close the braces and need to start after PHP variable as below:
<?php
echo 'Yes';
?>
Also you should wrap Dropdown and wise in braces as it will not work directly in get as you have used. Hope it helps you!
You can use combination of html with php inside:
<a href="limitdatabase.php?Dropdown=<?PHP echo $_GET[Dropdown] . "&search="
. $search_name . "&wise=" . $_GET[wise]; ?>">Yes</a>
Also, you can input whole link in string:
<?php
$mylink = "limitdatabase.php?Dropdown=" . $_GET[Dropdown] . "&search=" . $search_name . "&wise=" . $_GET[wise];
?>
YES

How to add a new line within JS confirm message to be shown on click of a link?

I'm trying to add \n but this breaks the onclick event – no message is popped up at all.
It works OK when I remove the \n character.
<?php
echo "<a href='logs.php?clear=true' onclick='return confirm(\"Are you sure:\n To delete this\");'>Clear</a>";
You need to use double backslashes, the first will be interpreted by PHP. Try this instead:
<?php
echo "<a href='logs.php?clear=true' onclick='return confirm(\"Are you sure:\\n To delete this\");'>Clear</a>";
Though you may want to use a heredoc instead:
<?php
echo <<< HTML
Clear
HTML;
Or, even better, use proper event binding like with jQuery:
<?php
echo <<< HTML
Clear
<script>
$("#clearconfirm").click(function(e) {
if (!confirm("Are you sure:\\n To delete this")) {
e.preventDefault();
}
});
</script>
HTML;

WPML |Get the current ICL_LANGUAGE_CODE with JS

I tried to retrieve the current ICL language with this code but it doesn't work.
var getLangCode = '<?php echo ICL_LANGUAGE_CODE; ?>';
alert(getLangCode);
Do you know how can I get the current language code with javascript ?
Thanks in advance !
You just need to place the quotes in the right places.
Remove quotes before <?php and after ?> and surround the PHP constant with double quotes.
var getLangCode = <?php echo '"' . ICL_LANGUAGE_CODE . '"' ; ?> ;
alert(getLangCode);
The accepted solution did not work for me. Actually, none of the solutions I've found which involved <?php or echo worked for me.
The workaround that worked for me was checking if the URL of the page contains the language code. Example for Spanish:
<script>
if(window.location.href.indexOf("/es/") > -1) {
alert("Spanish language");
}
</script>
You don't need DOM Ready for this, just place it on your header. Simple, right? :)

Javascript input issue

I have written a code for redirecting the page on submitting the form.
I have a drop down and textbox in that form.
I typed </script> as input for the textbox , which had lead to normal excution but with ); on screen.
this is what i got from my firebug tool
<script type="text/javascript">
loadSearch('Customer','
</script>
');
PHP CODE for submit
<?php
if($_POST['searchButton']){
echo "<script type='text/javascript'>loadSearch('".$_REQUEST['search_details']."','".$_REQUEST['search_input']."'); </script>";
}
?>
JAVASCRIPT
function loadSearch(selM,selK){
document.location.href="index.php?pg=search&selM="+selM+"&selK="+selK;
}//loadSearch
Note: $_REQUEST['search_input'] is the textbox and if the textbox is given with </script> as input
There is a severe vulnerability in you server side code. You should always clean strings which arise from user inputs using methods like htmlspecialchars.
Replace :
$_REQUEST['search_details']
and
$_REQUEST['search_input']
With :
htmlspecialchars($_REQUEST['search_details'], ENT_QUOTES, 'UTF-8')
and
htmlspecialchars($_REQUEST['search_input'], ENT_QUOTES, 'UTF-8')
Not doing this can make your website vulnerable where a malicious user could include scripts to snoop on your users. What this function does is convert special characters like < to html HTML character entities like < so that it can't be interpreted as code by the browser on the client side.
The problem is that you are dumping the request values into your page without doing any escaping of them. Since this is JavaScript, one quick fix is to use json_encode() to encode the values as JSON:
<?php
if($_POST['searchButton']){
echo "<script type='text/javascript'>loadSearch(".
str_replace(json_encode($_REQUEST['search_details']), '<', '\x3C') . ", " .
str_replace(json_encode($_REQUEST['search_input']), '<', '\x3C').
");</script>";
}
?>
Also, your function should be using encodeURIComponent():
function loadSearch(selM,selK){
document.location.href="index.php?pg=search&selM="+
encodeURIComponent(selM) + "&selK=" +
encodeURIComponent(selK);
}
But the question remains: if what you really want to do is redirect the user to a search page, why are you using this roundabout script approach in the first place? Why not just do a redirect directly from your PHP?
\Why do you not consider to use plain javascript without any php?
<input type="text" id="selM">
<input type="text" id="selK">
<input type="button" onclick="loadSearch(document.getElementById('selM').value,document.getElementById('selK').value);">

How to execute javascript without click or onload event from php?

I have one javascript named func.js, in that there is one function called show which takes 2 arguments, what I need to do is I want to call that function from php, I can't use any click or onload event here my script looks like this
<html>
<head></head>
<script type='text/javascript' src='path/to/func.js'></script>
<body>
some div etc
<form method='post' action="" >
.....
.....
</form>
</body>
</html>
<!-- after submit of form validation is in php -->
<?php
/* here I want to call javascript, where arguments are php variables
show('argument1','argument2'); */
// I tried to echo like this
echo "<script>show('$argument1',$argument2')</script>";
?>
So what's the solution for my case ?
The code you have should work… most of the time. Unfortunately, you haven't told us why it doesn't work - is there a PHP error? Is there a JS error? — and you haven't shown us either the resulting JavaScript that PHP is outputting or the contents of the variables so we can figure it out for ourselves.
The two most likely explanations (and the only ones that occur to me at the moment) for the problem are:
There is a problem with the data in the variables
That the variables contain characters which cannot appear inside JavaScript strings or ' characters which must be escaped inside JavaScript strings.
JSON is a sufficient subset of JavaScript that the json_encode function will escape (and quote) most data so it is suitable for use in JS.
<script>
show(<?php echo json_encode($argument1); ?>, <?php echo json_encode($argument2); ?>)
</script>
There is a problem with your timing
You have an HTML comment saying "after submit of form validation is in php", but there is nothing in the code you have shared to enforce that.
You need to have something like if (isset($_POST['some_data_from_your_form'])) { ... } wrapped around the generation of the script so it only appears when the form is submitted and not when it initially loads.
If that doesn't work, then you really do need to look at what the variables are, what the generated JS is, and what your JavaScript error console says.
Script elements are not allowed after the end of the HTML element. While browsers will recover from that error, you really should move the script inside the BODY.
It could be to do with the data inside the arguments, what sort of data is it?
echo "<script>show('".str_replace("'", "\'", $argument1)."', '".str_replace("'", "\'", $argument2)."')</script>";
If you're passing information such as J'min it will cause an issue. Does the data have multiple lines? Then it needs to be filtered.
First of all, your tags are broken
<script type='text/javascript' href='path/to/func.js'</script>
You should change href to src and close the script tag, so it becomes
<script type='text/javascript' src='path/to/func.js'>
Also, javascript is client-sided which means you can't call javascript functions in PHP.
I think a good solution here would be to use an AJAX call to validate your form.
Have you tried putting the arguments outside the quotes?
echo "<script>show('".$argument1."', '".$argument2."')</script>";
echo '<script type="text/javascript">show(' . $argument1 . ',' . $argument2 . ');</script>';
above might work for you.

Categories

Resources