Unable to post variables with jquery post()

后端 未结 2 1805
名媛妹妹
名媛妹妹 2021-01-29 08:29

I am trying to pass variables from a modal form to another page. I declare the variables from the form with the id tags in each selection.

Page reloads to test.php, howe

相关标签:
2条回答
  • 2021-01-29 08:58

    It's not clear how are you planning to use this code to pass values from your modal form but there are several problems with your current code:

    1. ; is missing at the end of variable assignment
    2. read values from input fields using val() instead of getting jquery objects of them
    3. use variable names in data object of post method instead of literals ("id", "name")

    Try this to see that variables are passed and echoed in a callback function

    var id = $( "#id" ).val(),
        name = $( "#name" ).val();
    
    $.post("jqtest/test.php", 
           { device_id: id, device_name: name },
           function(data){
                alert(data);
            }
    );
    
    0 讨论(0)
  • 2021-01-29 09:10

    It looks like there's a lot wrong with this... It looks like you are using echo $_POST['device_name']; and echo $_POST['device_id']; just to ensure that your AJAX is working. If that's the case, you don't need to be using .load();. You are also sending the jQuery object of $( "#id" ) and $( "#name" ) instead of the values within those form elements. Later, in your .post request, you have those same variables in quotes, which is sending the strings "id" and "name". Again - likely not what you're looking for.

    Your question is a bit convoluted but I'll do my best to answer. Try this JS:

    var id = $("#id").val(),
        name = $("#name").val();
    
    $.post("jqtest/test.php", { device_id: id, device_name: name }, function(response) {
        console.log(response);
    });
    

    In your PHP file, use this code:

    echo $_POST['device_name'];
    echo $_POST['device_id'];
    

    You will see your variables show up in the JS console of your browser. With this script, you've sent your two variables to test.php via POST and test.php will echo the results. The callback function added to the $.post request will display the output from test.php in the javascript console. Learn more about .$post() on the jQuery docs.

    0 讨论(0)
提交回复
热议问题