variable assignment open_form() codeigniter - javascript

just a simple question, can we assigned codeigniter open_form() to javascript var?
i have a code like this:
var openForm = '<?php echo form_open("controller/some_function",
array('class' => 'class_name', 'enctype' => 'multipart/form-data'));?>';
but when i run it, i got error in my console saying:
Uncaught SyntaxError: Invalid or unexpected token
but, when i try this:
var closeForm = '<?php echo form_close(); ?>';
it didn't show any error.
though i guess it's not about syntax error, i still have no idea what is wrong and what happens. can anyone explain?

Yes. You can use like this
var openForm = `<?php echo form_open("controller/some_function", array("class" => "class_name", "enctype" => "multipart/form-data")); ?>`;
openForm += '<?php echo form_close(); ?>';
$("#your_element)id").html(openForm);
In javascript You can't split a string across multiple lines. <?php echo form_open(); ?> add \n at the end which create Syntax error.
As well <?php echo form_open(); ?> adds double quotes, which also ends into escaping issues.
To avoid issues In such cases you can use the template literals which is `
For more details you can visit this site.
I hope it justifies your query.

Related

Copy php variable to a JavaScript variable cause Design issue

**This is my code **
I am sending copying data from a php variable to a JavaScript variable here
<?php
include('includes/config.php');
include('includes/classes/Artist.php');
include('includes/classes/Album.php');
include('includes/classes/Song.php');
if(isset($_SESSION['userLoggedIn'])){
$userLoggedIn = $_SESSION['userLoggedIn'];
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
// echo "<script>console.log('$userLoggedIn')</script>";
}else{
header('location:register.php');
And if i use the echo statement in the if statement here
it cause this. see the left side navigation bar;
Error image
And if i don;t use the echo statement the page is fine looks like this
Without error
I can't access the picture you uploaded right now, but I saw an error
echo "<script> var userLoggedIn = '" . $userLoggedIn . "'; alert(userLoggedIn); </script>";
Change the part we print on the screen in this way, data will be displayed on the screen.
I used this code inside the body of the html part and it works fine
<?php
if($userLoggedIn){
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
}
?>

SyntaxError: missing ; before statement - no obvious error?

I keep getting the above error referring to the second line of my code below and have no idea why! With the below part removed my project works ok with no problems but I keep gettig that error with it in, hence it wont run.
<?php
$myVar = $_POST['dropdown'];
?>
<script type="text/javascript">
var myVar = <?php echo '$myVar';?>
console.log(myVar);
</script>
This is probably your issue
var myVar = <?php echo '$myVar';?>
This should work, assuming you did want the single quotes around the PHP variable, and this also contains the javascript end-of-statement ; :
var myVar = <?php echo "'$myVar';";?>
If you did not want the single quotes then this should do :
var myVar = <?php echo $myVar . ';';?>

How to pass parameters with php in my case

I am getting an "Uncaught SyntaxError: Unexpected token ILLEGAL" error when try to load a page with a php variable.
$(document).ready(function() {
$.get("index.html", {token:<?php echo $token; ?>}, function(data) {
//codes..
});
});
I can't seem to echo $token in my javascript and I am sure $token is valid.
Can someone help me solve this issue? Thanks a lot!
You're echoing text from PHP into a Javascript context, which means you have to generate valid Javascript code. Simplest solution: json_encode()
{token : <?php echo json_encode($token) ?>}
json_encode() will take care of any quoting/escaping which needs to be done.
e.g. if $token = 'foo', then you'd be producing
{token: foo}
and be producing an undefined variable error.
you need to put quotes around the php output otherwise it will be treated as a javascript variable rather than a string
{token:'<?php echo $token; ?>'}

concatening PHP variable and strings inside double quotes for onclick event

The button when pressed call a function that needs the sn value, but the code below fails with the Chrome debug message:
Uncaught ReferenceError: Telephony is not defined
Telephony is one of the service names.
<html>
<head>
<title>someTitle</title>
<script>
function myF(varname) {
//I'll do here some other task with varname
console.log(varname);
}
</script>
</head>
<body>
<pre>
<?php
$sn='noname';
//here, the code to connect and select DB
while ($reg=mysql_fetch_array($registers))
{
echo "Service Name: ".$reg['sname']."<br>";
$sn = $reg['sname'];
echo "<button onclick=\"myF($sn)\">Vote</button>";
echo "<hr>";
}
mysql_close($conexion);
?>
</pre>
</body>
</html>
Is it possible a simple solution? My PHP server has PHP5
Assume your variable $sn is "Stack". Hence $sn is a string you need to pass this variable
as a string.
So rewrite myF($sn) as myF("'".$sn."'").
When yu inspect the button you can see myF('Stack').
then in javascript you can avoid the error.
Why do you need double quotes?
echo "<button onclick=\"myF($sn)\">Vote</button>";
Do this instead:
echo '<button onclick="myF(\''. $sn . '\')">Vote</button>';
Or perhaps do it with sprintf like this:
echo sprintf("<button onclick=\"myF('%s')\">Vote</button>", $sn);
Does this work?
echo "<button onclick=\"myF('$sn')\">Vote</button>";
I tried out a simple test case, without any MySQL. You can find the code I used below:
<?php
$sn='noname';
$registers = array(array('sname' => 'apple'), array('sname' => 'banana'), array('sname' => 'woodapple')); // Dummy "MySQL" Fetch Array (this might differ from what your 'while' loop receives)
foreach ($registers as $reg){ // In your case, a 'while' loop works.
echo "Service Name: ".$reg['sname']."<br>";
$sn = $reg['sname'];
echo "<button onclick=\"myF('$sn')\">Vote</button>"; // Added Quotes.
echo "<hr>";
}
?>
HINT: Please refrain from using mysql_* functions! They are deprecated!
Your concatenation need to change like this,
echo '<button onclick="myF("'.$sn.'")">Vote</button>';
I think that when you are passing the PHP variable as an argument in to the onclick event of button for calling javascript function, you string breaks because it is not quoted. So it needs to be quoted. I have edited the code line where you need to edit you code. So try like:
...
......
........
........
echo "<button onclick=\"myF("$sn")\">Vote</button>";
.......
......
....

php echo of javascript with php echo inside

I am very new to PHP and JavaScript. I am currently using echo in PHP to run some JavaScript on the page. I need to make a new javascript array and a new variable that are equal to an existing PHP array and variable, so I did this:
var messages = <?php print_r($messages)?>
var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>
However, there is a problem caused by my using echo to echo script containing echo. How would I solve this. I would like to echo it because it is only about 4 lines long, so is there an alternative.
Thank you in advance.
Edit: This is the whole JavaScript. It is for a messaging system. $messages is declared from another PHP function, and the basic aim of this code is to 'refresh' the echo every few seconds so that the user can see new messages without having to refresh their page:
echo '<script type="text/javascript">;';
echo 'var messages = <?php print_r($messages)?';
echo 'var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>';
echo 'setInterval(function(){console.log("hello")},3000);';
echo '</script>';
Not getting what you want,but if you want to use php array in javascript than make it javascript array
<script>
<?php $test_arr = array('apple','banana','mango');?>
var js_array = <?php echo json_encode($test_arr);?>;
</script>
output
<script>
var js_array = ["apple","banana","mango"];
</script>
Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.
The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.
By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.

Categories