Well, I need to insert a HTML string with php code inside in a form.
I have one form to create new users. Inside of it, I need to insert a role for this user, so I have some roles in my database to apply to him.
I have a html select field to do that, and a button to add a new rol. When I click in the button, I want to add a new select field to my form. But inside this code I have PHP code to show all roles. I try this way using jQuery:
$(document).ready(function () {
$('#add-role').click(function (event) {
var newRoleField = "<label for=\"usuario_perm_id\">ROLE <span class=\"required-field\"> * </span>:</label>" +
"<select id=\"usuario_perm_id\" name=\"usuario_perm_id\" tabindex=\"7\">" +
"<option <?php echo ($this->usuario[\"rol_id\"] == \"none\" ? 'selected=\"selected\"' : null); ?> value=\"none\">-- Seleccione un rol --</option>" +
"<?php foreach ($this->roles as $rol): ?>" +
"<option value=\"<?php echo $rol[\"rol_id\"]; ?>\" <?php echo ($this->usuario[\"rol_id\"] == $rol[\"rol_id\"] ? 'selected=\"selected\"' : null); ?>><?php echo $rol[\"nombre\"]; ?></option>" +
"<?php endforeach; ?>" +
"</select><br />";
$('#new-roles').append(newRoleField);
event.stopPropagation();
event.preventDefault;
});
});
And I get a new select field but inside it, the text:
usuario["rol_id"] == "none" ? 'selected="selected"' : null); ?> value="none">-- Select role --
You can't. JavaScript (and thus also jQuery) runs client side and PHP runs server side. The browser has no idea how to handle any PHP you might insert.
A way to handle this, is to have jQuery query the server for the roles and have your server create a (PHP generated) list of roles. Check out AJAX.
You can't insert server side code (PHP) on the client (Javascript).
You can load the data from PHP into a JS variable when the page first loads up and then load from there.
I don't know how it works exactly with JQuery (I used it with pure JavaScript), but look for AJAX.