JS alert function with multiple line string - javascript

I have a php function which generates a javascript alert popup.
This function accepts a parameter message.
My problem is that if message is a multiple line string, javascript won't alert the text because of the lack of '+' every line. How can I solve that?
function alert($msg) {
echo '<script type="text/javascript">alert("'.$msg.'")</script>';
}
/* DOESN'T WORK */
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.
testtesttesttesttesttesttesttest.
testtesttesttesttesttesttesttesttesttest.';
alert($msg);
/* WORKS */
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest. testtesttesttesttesttest. testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttesttestttesttesttesttesttesttest.';
alert($msg);

The problem is multiline strings in javascript need to be split with a \ at the end of each line.
function alert($msg) {
echo '<script type="text/javascript">alert("'.$msg.'")</script>';
}
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.\
testtesttesttesttesttesttesttest.\
testtesttesttesttesttesttesttesttesttest.';
alert($msg);

Please user json_encode function in pass function parameter
json_code function is change link break into \n
<?php
function alert($msg) {
echo '<script type="text/javascript">alert('.$msg.')</script>';
}
/* DOESN'T WORK */
$msg = 'testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest.
testtesttesttesttesttesttesttest.
testtesttesttesttesttesttesttesttesttest.';
alert(json_encode($msg));
?>
This chrome

Related

php ja javascript links and encoding

With scandinavian letters and when encoding them, I have a problem. With code below, javascript add some extra encoding to variable
<script>
function doit(params) {
var url = "/linkto/code.php" + params;
window.open(url,"Doit","width=750, height=600");
}
</script>
<?php
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
echo 'Do it!'; // link to page
?>
When changing code above to php, changed does not happened and problem go away.
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
// link to page
echo '<a href="/linkto/code.php"'.$param.'>Do it!</a>';
Hi all again,
I cannot make it work, no difference between utf-8 or iso-8859-1.
Result is something else, when using javascript-function or direct link.
You can try it here:
http://www.ajl.fi/tmp/test.php
Here is codes:
test.php:
<script type="text/javascript">
function doIt(params) {
var url = "doit.php" + params;
window.open(url,"doit");
}
</script>
<?php
$var1 = 'pähkinä';
$var1 = urlencode($var1);
echo sprintf("Do it - call",$var1)."<br>";
echo sprintf("Do it - link",$var1);
?>
and here is doit.php:
<?php
var_dump($_GET);
?>
In ist code, you have two issues in this code
1) Short tag will not work inside the <?php ?> here:
echo 'Do it!'; // link to page
2) You forgot to add quotes here:
window.open(url,"Doit",width=750, height=600"); //missing quote here
Modified Code:
<?php
$var1 = 'p%E4hkin%E4';
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
?>
Do it!
<script type="text/javascript">
function doit(params) {
var url = "/linkto/code.php" + params;
console.log(url);
window.open(url,"Doit","width=750, height=600");
}
</script>
I answer to myself - Solved.
IE, Edge and Chrome, all working ok on both cases. Firefox has a problem. When using
Do it!
result is not correct, but when using
Do it!
seems to work on all browsers

Is It possible to call a JavaScript function when I assign a value to a PHP variable?

As soon as I assign a value to my PHP variable $msg...
$msg = 'Some message';
... I want to call a JS function like this :
function showSuccess() {
alert('success')
}
Is it possible ?
If I understand you correctly, this will be the answer for your question.
$msg = 'some value your are going to assign';
if($msg) //checking $msg variable has some value or not
{
print '<script type="text/javascript">showSuccess()</script>';
/* or */
print '<script type="text/javascript">alert("succeess")</script>';
}
From what I understood, I think you would like to display a JS alert box when a desirable value is assigned to $msg. The following code may help.
<?php
$msg="Hello";
/*this is just to give you an idea
and so I am considering value of
$msg as hardcoded*/
if($msg!="")
/*may vary with the variable type,for
example if($msg!=0) in case of int*/
{
echo "<script>alert('successfull');</script>"
/*echo adds stuff to the html
document on the go*/
/*the above JS code will be added to
the HTML document and executed
to display an alert box*/
}
?>
The basic structure remains the same even if the value of $msg is not hardcoded in your case. Only the condition in if may vary depending on the variable type.
You could also use if($msg). This simply checks if $msg has been assigned a value or not.
if($msg!)
//universal-checks if value is assigned
{
echo "<script>alert('successfull');</script>"
}
Maybe something in DOM like this, to keep php and javascript separate:
<?php
//assign your value
$value = true;
?>
<input id="value" type="hidden" value="<?php if ($value) { echo 'true'; } ?>" />
<script>
var value = document.getElementById('value').value;
if (value) {
alert(value);
}
</script>

SyntaxError: unterminated string literal

Hello i have a script php and javascript, i want call my function javascript from php, but i have a problem when my string have a new line, when i turn firebug in firefox
this error is
"SyntaxError: unterminated string literal"
This is my code
<script>
function myfunction(mydata)
{
alert(mydata)
}
</script>
<?php
$data =nl2br("hello \n world");
echo 'Click';
?>
Help Me, Thank's
Fixed
<script>
function myfunction(mydata)
{
alert(mydata)
}
</script>
<?php
$data = str_replace("\n", '\n', "hello \n world");
$data = preg_replace( "/\r|\n/", "", $data);
echo 'Click';
?>
Add an additional treatment to your string to remove line breaks :
$data = nl2br("hello \n world");
$data = preg_replace( "/\r|\n/", "", $data );
Then echo
echo '';
instead of
echo '';
Add and escape simple quotes between the variable for javascript ton consider it a string
concat your var to the outputed string because between simple quotes, it will not be interpreted (on the contrary of double quotes).
Then if you just want to add a line break directly in the alert, you should just do the following :
$data = "hello \\nworld";
echo 'Click';
If you want to display HTML into an alert box, consider using a popin javascript plugin.
As mentioned in the comments, single quotes will not interpret variables. You need to switch your quote types around, and add quotes around the data variable:
echo "";

Redirect to a page/URL after alert button is pressed

i have referred to this two questions call php page under Javascript function and Go to URL after OK button in alert is pressed. i want to redirect to my index.php after an alert box is called. my alert box is in my else statement. below is my code:
processor.php
if (!empty($name) && !empty($email) && !empty($office_id) && !empty($title) && !empty($var_title) && !empty($var_story) && !empty($var_task) && !empty($var_power) && !empty($var_solve) && !empty($var_result)) {
(some imagecreatefromjpeg code here)
else{
echo '<script type="text/javascript">';
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
echo '</script>';
}
it's not displ ying anything(no alert box and not redirecting). when i delet this part echo 'window.location= "index.php"'; it's showing the alert. but still not redirecting to index.php. hope you can help me with this. please dont mark as duplicate as i have made tose posts as reference. thank you so much for your help.
You're missing semi-colons after your javascript lines. Also, window.location should have .href or .replace etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
if (window.confirm('Really go to another page?'))
{
alert('message');
window.location = '/some/url';
}
else
{
die();
}
window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location = "index.php";';
echo '</script>';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL
(AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.
Let me suggest that you do this another way..
echo '<script type="text/javascript">\n';
echo 'alert("review your answer");\n';
echo 'document.location.href = "index.php";\n';
echo '</script>\n';
1) prepare to accept a modification or addition to the current Javascript cache.
2) show the alert
3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.
Best of luck!
Like that, both of the sentences will be executed even before the page has finished loading.
Here is your error, you are missing a ';'
Change:
echo 'alert("review your answer")';
echo 'window.location= "index.php"';
To:
echo 'alert("review your answer");';
echo 'window.location= "index.php";';
Then a suggestion:
You really should trigger that logic after some event. So, for instance:
document.getElementById("myBtn").onclick=function(){
alert("review your answer");
window.location= "index.php";
};
Another suggestion, use jQuery
Working example in php.
First Alert then Redirect works.... Enjoy...
echo "<script>";
echo " alert('Import has successfully Done.');
window.location.href='".site_url('home')."';
</script>";
<head>
<script>
function myFunction() {
var x;
var r = confirm("Do you want to clear data?");
if (r == true) {
x = "Your Data is Cleared";
window.location.href = "firstpage.php";
}
else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>
<p id="demo"></p>
</body>
</html>
This will redirect to new php page.

Using JS within PHP for an if window.width issue

I'm wanting to echo some code based on whether the user is on a mobile device (less than 768px) or larger.
I have done the following:
<?php
if ( is_home() ) {
?>
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("<?php echo my_shortcode("[mobile-slider]"); ?>");
} else {
document.write("<?php echo my_shortcode("[desktop-slider]"); ?>");
}
</script>
<?php
} else {
//do the stuff for the other pages
} ?>
But now when the homepage renders it displays "); } else { document.write(" then the homepage slider and then "); }. Any idea why?
JS error
SyntaxError: unterminated string literal
document.write('
HTML Output - Seems to be adding a line break which I think is breaking the script?
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("
<!--slider-->
"<?php echo my_shortcode("[mobile-slider]"); ?>"
CHANGE TO
"<?php echo my_shortcode('[mobile-slider]'); ?>"
^ ^ // changed quotes here
or escape quotes
"<?php echo my_shortcode(\"[mobile-slider]\"); ?>"
try this:
document.write(<?php echo "\"[mobile-slider]\""; ?>);
Well your quotes are definately off, as others have mentioned, your inner quotes must be different from the outer ones, or escaped.
Is it possible for you to run your php function in the main document(outside of the javascript), then choose to show/hide/alter its contents with the javascript?
If that's not possible, try calling your function directly, instead of through the do_shortcode hook.
As a final alternative, you may need to use an ajax call here. I don't know that you're able to call shortcodes the way you're attempting to do here.

Categories

Resources