Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate string in Jquery and PHP

In the code below, how do you concatenate the variable c to the string name so that the PHP function foo() will actually read foo('name1') since the value of c in this case is 1?

$(function(){

var c = 1;

$('#foo').click(function() {
    $('#bar').append('<div style="color:red">\n\
                        Name:<?=foo('name')?>\n\
                    </div>');   
    c++;
    });
});

Edit:

All foo() does is return the string (e.g, name1 or name2) depending on c's value. What I actually need is just something like this <?=foo('name' + c)?> however that doesn't work.

like image 501
IMB Avatar asked Dec 17 '25 01:12

IMB


1 Answers

PHP happens on the server side and javascript happens on the client side so you can't actually do this. If you want to use the results of a php method called with a value updated in javascript, you have to use ajax. Something like this:

var c = 1;

$('#foo').click(function() {
    $.ajax({
        url: 'something.php?c=' + c,
        success: function(name) {
            $('#bar').append('<div style="color:red">\n\
                Name:' + name + '\n\
            </div>');   
        }
    });

    c++;
});

Here, something.php will accept a single request parameter "c", and should output only:

<?= foo('name' . $_GET['c']) ?>
like image 143
Ben Lee Avatar answered Dec 19 '25 18:12

Ben Lee