简体   繁体   中英

Pass variable from Ajax to PHP does not work

I have such code

<form>
        <input type="text" value="" name="someval">
        <button id="ajax-button">ajaxButton</button>
    </form>

    <script>
        $(document).ready(function(){
            $('#ajax-button').click(function(e){
            e.preventDefault();
                $.ajax({
                  type: "GET",
                  url: "action.php",
                  data: { text : $('input[name=someval]').val() },
                  dataType: "text",
                  success: function (data){
                    alert(data);
                  }
                });         

            });
        });
    </script>

Now I try to echo the Ajax returned value in php.

I try

echo json_encode($text);
echo $text; 
echo $_GET['text'];

Al are wrong.

How to get it in PHP. Thanks

Set attributes for the form to get semantic correct html

<form action="action.php" id="someForm" method="POST">
    <input type="text" value="" name="someval">
    <select id="someSelect">
        <option value="some_1">some 1</option>
        <option value="some_2">some 2</option>
        <option value="some_3">some 3</option>
    </select>
    <button id="ajax-button">Send</button>
</form>

Your script

<script>
    $(function(){

        var form = $("#someForm"),
            select = $("#someSelect"),
            url, formData;

        form.submit(function(event){
            event.preventDefault();

            url = form.attr("action");
            formData = form.serializeArray();

            $.post(url, data, function(response){
                console.log($.parseJSON(response));
            });
        });

        select.change(function(){

           url = form.attr("action");
           formData = form.serializeArray();

           $.post(url, data, function(response){
                console.log($.parseJSON(response));
            });                   
        });

    });
</script>

Your php file(path to file set in action attribute of the form).

<?php

    var_dump($_POST);

?>

Use data: 'text=' + $('input[name=someval]').val() , instead. And in PHP you can directly access it using echo $_GET['text']; only without the need of json encoding it.

Otherwise the syntax of json is data: { "text" : $('input[name=someval]').val() }, .

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