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 --
-
exactly how do you expect your browser to run this php code? Are you going to require that all users run a custom browser that has a PHP engine built into them? remember... PHP is a server-side language. it's just random garbage as far as a browser is concerned....Marc B– Marc B2013年01月28日 14:50:18 +00:00Commented Jan 28, 2013 at 14:50
-
1PHP is interpreted server-side, not client-side. You can't use JavaScript to include PHP code. It's not clear what you're trying to do here, but you're either going to have to perform the server-side logic in a post-back of the page and re-render the page or include values from PHP into the JavaScript and use those values client-side.David– David2013年01月28日 14:51:00 +00:00Commented Jan 28, 2013 at 14:51
3 Answers 3
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.
1 Comment
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.
Comments
I don't know how it works exactly with JQuery (I used it with pure JavaScript), but look for AJAX.