I have this little piece of code and I would like to pass the value to PHP.
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
Is there a way to do this? (new at jQuery)
Many thanks!
No you cannot. JQuery plays on client and php on backend.
If you want to pass some values from Client (Jquery/Js) to Backend (PHP), you need to either submit a form or make an AJax call to server.
You should research about jQuery ajax . This can be your solution for sending data to server from client.
check this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
$.ajax({
type: "POST",
url: 'edit.php',
data: "window_size=" + size,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
alert(result)
}
});
</script>
then create edit.php
<?php
print_r($_REQUEST);
?>
if you want to save this value then use this code
<?php
session_start();
echo $_SESSION['php_value'];
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var size;
if ($(window).width() < 960) {
size = "1";
} else {
size = "2";
}
$.ajax({
type: "POST",
url: 'edit.php',
data: "window_size=" + size,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
alert(result);
//window.location.reload();
}
});
</script>
and update edit.php as like
<?php
session_start();
$_SESSION['php_value'] = $_REQUEST['window_size'];
echo $_SESSION['php_value'];
?>
you want to see this value or use then refresh this page if you want to use this variable in other page then use this
//first page first set it
$_SESSION['php_value'] = $_REQUEST['window_size'];
//second page or other page and use it
$var_value = $_SESSION['php_value'];
Yes. Use the code below to send the value of size to your php script:
var ajax_call = $.ajax({url: '/your_php_script.php', data: 'size='+size, success: function(data) {
}});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.