سؤال

This is really basic. All I want to do is measure the html width of a browser window, and pass that data to a PHP script so that I can adjust what information is passed to the site.

I've got the HTML width part down. I'm just having trouble passing the Javascript/jQuery variable to the PHP script using AJAX.

Here's the Javascript/jQuery. It is written in PHP so that I can use the include() function later.

echo 
'<script> 
    htmlWidth = $("html").width();
    $.ajax({
        type: "POST",
        url: "mobileView.php",
        data:{ width: htmlWidth }
    }) 
</script>';

And here's the PHP:

$width = $_POST['width'];
function mobileView(){
    if ($width < 950){
        return true;
    } else{
        return false;
    }
}
mobileView();
هل كانت مفيدة؟

المحلول

Here is the code that can be function within a file:

For PHP part, you should pass value to the function and call the function.

I guess you need return data to the client from the php function return. Then, for ajax part, you have to catch the return data.

<?
if(isset($_POST['width'])){
    $width = $_POST['width'];

    function mobileView($width){
        if ($width < 950){
            echo 'true';
        } else{
            echo 'false';
        }
    }
    mobileView($width);

}else{
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script> 
    htmlWidth = $("html").width();
    $.ajax({
        type: "POST",
        url: "mobileView.php",
        data:{ width: htmlWidth }, 
        success: function(data){
            console.log(data); 
        }
    })
</script>

<?
};

?>

نصائح أخرى

Try this.

Your AJAX

htmlWidth = $("html").width();
$.ajax({
    type: "POST",
    url: "mobileView.php",
    data:{ width: htmlWidth, somevar : "yes" },
    success: function(data){
        console.log(data); 
    }
})

Your PHP

if(isset($_REQUEST['somevar'])){
     $width = $_POST['width'];

    function mobileView($width){
        if ($width < 950){
            echo 'true';
        } else{
            echo 'false';
        }
    }
    mobileView($width);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top