0

I get the variable in php file: like

$segmentData = $loadData['segment'];
echo $segmentData;

How can I use this value to insert/ append to span element in jQuery?!?!

I tried to place it in span element created in php file, and than extract via ID with jQuery, but didnt work.

I assume there must be better solution to this. EDIT:

I am using it with ajax call with WP. I got in callback function requested data, but now I want to display that data in div or span on the fronted. So far, I have made span

<span id="segment"> <?php echo $segmentData ;?></span>

and in js on click get value of id "segment", and than append, but I dont wanna to make html element in php file, and this one that I tried didnt retrieve me value

Please ask me if you need more info

user3042036
  • 325
  • 1
  • 2
  • 14

3 Answers3

3

The easiest way is this:

<?php
     $segmentData = $loadData['segment'];
?>
...
<script language="javascript" type="text/javascript">
     var str = "<?= echo $segmentData ?>";
</script>

If you're using AJAX you can do it like this (especially if you want to load a php variable from another file)

get-data.php

<?php
   $segmentData = $loadData['segment'];
   echo $segmentData;
?>

index.php (or whatever the actual page is named like)

$.ajax({
  type: "GET",
  url: 'get-data.php',
  success: function(data){
    $('#idOfYourSpan').text(data.response);
  },
  error: function(e, d, l){
    console.log(e);
  }
});

There is a longer, more in-depth answer here: How to pass variables and data from PHP to JavaScript?

Community
  • 1
  • 1
levon
  • 940
  • 11
  • 15
  • 1
    Sidenote: `= echo`? `=` which is identical to ` echo` therefore it should read either as `` or `= $segmentData ?>` - From the manual http://php.net/manual/en/ini.core.php#ini.short-open-tag – Funk Forty Niner Jul 21 '14 at 14:39
0

Try this with Jquery:

$('#idOfYourSpan').text('<?php echo $segmentData; ?>');

Your file must have '*.php' as an extension

spencer
  • 434
  • 4
  • 8
0
<script> 
var val = <?php echo  $segmentData;?>
 $('span').text(val);
</script>
shefali
  • 85
  • 1
  • 9