1

I want to call a jQuery variable in PHP syntax.

$('.card').on('click', function() {
cardID = $(this).attr('id');
$('#card-front-img').html('<img src="{{ asset("public/nfc-assets/cards-imgs/'+cardID+'/front-preview.png") }}">');

at +cardID+ I want to pass card id dynamically. But by this code, It print +cardID+ as a string.

4
  • 1
    what is the datatype of javaScript variable you are passing? Commented Oct 20, 2017 at 6:22
  • for example: cardID = 'aquaBlue'; Commented Oct 20, 2017 at 6:27
  • in your example, cardID is a string, so there is nothing wrong here Commented Oct 20, 2017 at 6:28
  • I dont understand what php have to do with this question? i only see jquery being used Commented Oct 20, 2017 at 6:36

3 Answers 3

1

You actually can't pass js-variable into blade syntax since you can't execute browser code in a php code. You have to change approach. Manipulate with img path right in the js code.

$('.card').on('click', function() {
    var cardID = $(this).attr('id');
    var imgPath = '{{ asset("public/nfc-assets/cards-imgs/cardID/front-preview.png") }}';
    $('#card-front-img').html('<img src="' + imgPath.replace('cardID', cardID) + '">');
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can pass JavaScript variable directly.

However you can create asset url with a placeholder, which can be replaced later.

$('.card').on('click', function () {
    //Create a URL with placeholder
    var str = '{{ asset("public/nfc-assets/cards-imgs/__REPLACE_WITH_CARD_ID__/front-preview.png") }}';

    //Replace placeholder with card id
    str = str.replace('__REPLACE_WITH_CARD_ID__', $(this).attr('id'));

    //Use variable
    $('#card-front-img').html('<img src="' + str + '">');
});

Comments

0

I see your problem,

Your problem is not php, but the way you append the variable,

Remove your blade syntax since it is not recognize inside jquery and also rewrite your quotes,

Replace it with this

$('#card-front-img').html("<img src='/public/nfc-assets/cards-imgs/"+cardID+"/front-preview.png'>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.