简体   繁体   中英

Passing parameter to request via ajax and printing it with php

I have in my index.php:

<script type="text/javascript">

    var chosenCity = 'London';

    (function($) {

        var formData = new FormData();

        formData.append("city", chosenCity);

        var xhr = new XMLHttpRequest();
        xhr.open("POST", "index.php");
        xhr.send(formData);     

    })(jQuery);


</script>

I want to print in my page the value of chosenCity, so I do:

<?php 
    $var = $_REQUEST['city'];
    echo $var;
    print_r($_POST);
    print_r($_REQUEST);
?>

But nothing is printed.

Using a php debugger I can see that $var contains null at first load, in a fisrt debug session.

And in a second debug session $var contains 'London' ... nevertheless nothing is printed even after this second session.

The same happens trying to print $_POST and $_REQUEST

I've tried different environments and browsers

What am I doing wrong?

Is there any other way to do it?

Ignoring the jQuery for a moment the following works fine which suggests that your javascript code for sending the XHR request itself is fine.

    <?php
        /* 

            "/test/target.php" ~ equivilent of index.php

        */
        ob_clean();
        print_r($_POST);
        exit();
    ?>


    function _ajax( chosenCity ){
        var fd = new FormData();

        fd.append('city', chosenCity);
        fd.append('section','baselevel');

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange=function(){
            if( xhr.readyState==4 && xhr.status==200 ) console.info( 'Response: %s',xhr.response );
        };
        xhr.open( 'POST', '/test/target.php' );
        xhr.send( fd );     
    }

    document.addEventListener( 'DOMContentLoaded', function(){ _ajax.call(this,'london') }, false );

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM