smoke smoke - 5 months ago 16
jQuery Question

PHP inside a JQuery function issue

I'm trying to add the php code below to the

value=""
attribute inside the jquery function but when I run the html code the PHP code itself is displayed I was wondering how can I fix this problem so the PHP code itself is not displayed?

Jquery

$(document).ready(function(){
var max_fields = 2;
var x = 1;

$('.add').click(function(e){
//e.preventDefault();
e.preventDefault();
//stop the click from bubbling
e.stopPropagation();

if(x < max_fields){
x++;
$(this).closest('li').append('<div class="container"><input type="text" name="first_name[]" value="" /></label></div>');
}

});


PHP

<php if(!empty($_POST['first_name'])){ echo $first_name; } ?>

Answer

You're trying to use PHP code in a .js file, but that won't work. PHP is normally only executed in .php files, and even if you configure your webserver to execute PHP in a .js file, it won't have acecss to the original script's $_POST variables.

What you can do is set a Javascript variable from the original .php file, and then use that in the .js file.

<script>
var first_name = <?php echo json_encode($_POST['first_name']); ?>;
</script>
<script src="filename.js"></script>

Then in filename.js you can use the first_name variable:

$(document).ready(function(){
    var max_fields = 2;
    var x = 1;

    $('.add').click(function(e){
        //e.preventDefault();
        e.preventDefault();
        //stop the click from bubbling
        e.stopPropagation();    

        if(x < max_fields){ 
            x++;    
            $(this).closest('li').append('<div class="container"><input type="text" name="first_name[]" value="' + first_name + '" /></label></div>');    
        }

});
Comments