Use a PHP Variable in Jquery

How to access PHP variables in JavaScript or jQuery rather than ?php echo $variable ?

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction.
jQuery.ajax is a good start IMHO.

Use a PHP variable in JQuery

What you could simply do is use your PHP to echo out the code to initiate a JavaScript variable.

<script type="text/javascript">
<?php

$phpVar = "foo";
echo "var phpVariable = '{$phpVar}';";

?>
</script>

Once the PHP code is parsed, and the HTML is sent to the user - all they will see is the result of the PHP echo -

<script type="text/javascript">
var phpVariable = 'foo';
</script>

Now your phpVariable is available to your JavaScript! So you use it like you would in any other case -

$("div."+phpVariable);

That will retrieve us any <div> element with a foo class -

<div class="foo"></div>

Calling a PHP variable in jQuery

You have two or three options: if the Javascript is in the php file, you can

var phpVar = <?php echo $var; ?>;

Otherwise if the Javascript is anywhere at all, you can do:

<input type="hidden" id="phpVar" value="<?php echo $var; ?>">

and then access it as

$('#phpVar').val();

Example 1:

jQuery(document).ready(function($){
$('#image1').addimagezoom({ // single image zoom
zoomrange: [3, 10],
magnifiersize: [800,300],
magnifierpos: 'right',
cursorshade: true,
largeimage: <?php echo $var; ?> //we add the directory of the image.
});
});

Example 2:

Html:

<input type="hidden" id="phpVar" value="<?php echo $var; ?>">

Javascript

jQuery(document).ready(function($){
$('#image1').addimagezoom({ // single image zoom
zoomrange: [3, 10],
magnifiersize: [800,300],
magnifierpos: 'right',
cursorshade: true,
largeimage: $('#phpVar').val(); //we add the directory of the image.
});
});

Can I use php variable in jquery

You can, but the PHP output is a string, so you must enclose it in double quotes:

var phpString = "<?php echo json_encode($clean); ?>";

As it is a string, you have to parse it with JSON.parse(), so it becomes a Javascript object/array you can work with:

var data = JSON.parse(phpString);

for ( var i = 0; i < data.length; i++ ) {
console.log(data);
}

EDIT: $cleanis a string, so there's no need to json_encode() it. I worked the answer as if it was an array, so we'll create one (two actually: one array for the data of each line and another global one that will save the data of the whole file -a.k.a array of arrays-). Add an array just before your echo '<select...>'; and we'll add every string read in the file to it:

//loop through the csv file

echo '<select name="box" size="7" multiple="multiple">';
$file_lines = array(); // Global array
while (($line = fgetcsv($handle, 1000, ',')) !== false) {
$strings = array(); // Here, create an array for this particular line
foreach($line as $cell) {
$clean = htmlspecialchars($cell);
array_push($strings, $cell); // Add the string to the array
echo << < OPTION <
option value = "{$clean}" > {
$clean
} < /option>
OPTION;
}
array_push($file_lines, $strings); // Add the line data to the global array
}

Then below, instead of var phpString = "<?php echo json_encode($clean); ?>";, you should use:

var phpString = "<?php echo json_encode($file_lines); ?>";

And the rest of the answer should work well.

Pass a php variable to a jQuery function

Suppose your $variable has value "Hello".

Then this code:

echo 'wholesection('.$variable.');',

is rendrered in html like

wholesection(Hello);

See? You're passing Hello to a function. Not "Hello" but Hello.
And Hello is considered a javascript variable. I bet you don't have it.

So, the fix is - add quotes:

echo 'wholesection("'.$variable.'");',

which will be rendered as:

wholesection("Hello");

echo php variable inside jQuery function

You have to assign the php values first to js variables in .php file

<script>
START_Date='<?php echo json_encode($datestart); ?>';
END_Date='<?php echo json_encode($dateend); ?>';

</script>

Now in your js file

jQuery(function() {
jQuery("#datetimepicker").datetimepicker({
format: "dd MM yyyy - HH:ii P",
showMeridian: true,
autoclose: true,
startDate: START_Date,
endDate: END_Date,
minuteStep: 15,
pickerPosition: "bottom-left"

});
});

OR include your js code in your php file then you can directly use php variables inside your js like this:

jQuery(function() {
jQuery("#datetimepicker").datetimepicker({
format: "dd MM yyyy - HH:ii P",
showMeridian: true,
autoclose: true,
startDate: '<?php echo json_encode($datestart); ?>',
endDate: '<?php echo json_encode($dateend); ?>',
minuteStep: 15,
pickerPosition: "bottom-left"

});
});

Accessing PHP variable in jQuery with CodeIgniter

Try this

do one thing.. you need to create two input hiddent field in view.
like this

<input type='hidden' id="amazon" value="<?php echo $is_amazon; ?>" />
<input type='hidden' id="ebay" value="<?php echo $is_ebay; ?>" />

and call that value in you jquery lik this

$(document).ready(function() {

//alert($('#amazon').val()+" "+$('#ebay').val());

console.log("amazon"+$('#amazon').val());
console.log("ebay"+$('#ebay').val());
});

now it will work for u.. try it.

Variable from PHP into jQuery to form a link

Because you added an inline js event handler function I would suggest to use the parameters:

  • event: the event object
  • this: the current element

In your case your may write:

<tr class="trash" onclick="deletePopUp(event, this)" data-id="This is An ID">

Therefore, your deletePopUp function will be:

function deletePopUp(e, ele) {
var id = ele.dataset['id']; // get current data-id
$('#delete').attr('href','/assets/scripts/delete-user.php?id='+id);
$('#myModal').modal('show');
}

The snippet:

function deletePopUp(e, ele) {  var id = ele.dataset['id'];  $('#delete').attr('href','/assets/scripts/delete-user.php?id='+id);  $('#myModal').modal('show');}

$('#delete').on('click', function(e) { e.preventDefault(); console.log(this.href);});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"><script src="https://code.jquery.com/jquery-2.1.1.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<table id="myTable"> <tr class="header"> <th>Naam</th> <th>Bedrijf</th> </tr> <tr class="trash" onclick="deletePopUp(event, this)" data-id="This is An ID"> <td>name</td> <td>company</td> </tr></table><!-- The Modal --><div id="myModal" class="modal">
<!-- Modal content --> <div class="modal-content"> <div class="modal-top"> <h1>Weet je het zeker?</h1> <span class="close">×</span> </div> <div class="modal-inner"> <a href="delete-user.php?id=<?php echo $id; ?>" id="delete" class="btn-confirm">Verwijderen</a> <a href="#" class="btn-cancel cancel">Annuleren</a> </div>
</div>
</div>

How to pass php variable's value to jquery

It really depends if you are using some sort of a template engine.

  1. If you're using plain PHP, the only option for you is to echo the variable:

    var current page = "<?php echo $your_var; ?>";
  2. Twig engine:

    var current page = "{{ your_var }}";
  3. Smarty and RainTPL engines:

    var current page = "{$your_var}";

As you can see, there are other ways. All of them work fine. It really depends on how you'd like to write and organize your code. I personally use Twig and find it really easy,fast and straightforward.

Also, as others have pointed out, you can do AJAX calls to the server and fetch the variables like that. I find that method time-consuming, inefficient and insecure. If you choose this method, you will be posting requests to a script. Everybody will be able to do post/get requests to that script which opens your doors to some bots and DoS/DDoS attacks.

how to access php variable with jquery

$('.add_to_cart').on('click',function(){
alert($(this).closest('.product').find('.id').val())
})


Related Topics



Leave a reply



Submit