procatmer procatmer - 4 months ago 26
Javascript Question

variable assignment open_form() codeigniter

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?

Answer

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.

Comments