Saving form variables onchange with ajax

2019-07-20 13:08发布

问题:

I'm trying to save form data into $_SESSION variables with ajax, but I can't seem to run the onchange event properly or send the variable.

The form length varies, so I've tried to use dynamic variables.

<script>
    function orderValues(boxValue){
        $.post("/ajaxConnect.php",{value: $("qty_" + boxValue).val()}, 
        function( result ) {
            console.log('value saved');
        });
    }
</script>

<php
    echo "<div id=\"prodBox\">QTY: <input name=\"qty_".rawurldecode($item->LINE)."\" value=\"" . $_SESSION['box_']['qty_'.rawurldecode($item->LINE)] . "\" type=\"number\" onchange=\"orderValues(this.value)\"/></div>";
?>

ajaxConnect:

<?php
    session_start();
    $_SESSION['box_']['value'] = $_POST["value"];
?>

The end goal is for input values to be saved to $_SESSION['box_']['qty_LINE'] whenever the value is changed.

If I set the $_SESSION value manually I can get it to show, but not through ajax.

Cheers for any help.

回答1:

It is a better practice to use jquery to do the event bindings instead of using attributes like onchange, and you also need to make sure you get the right values to send to your server, you need both the line name and the value.

So remove the onchange attribute:

<php
    echo "<div id=\"prodBox\">QTY: <input name=\"qty_".rawurldecode($item->LINE)."\" value=\"" . $_SESSION['box_']['qty_'.rawurldecode($item->LINE)] . "\" type=\"number\" /></div>";
?>

And use this jquery code:

$(document).ready(function(){
    $('#prodBox input').change(function(){
        $.post("/ajaxConnect.php",{line: this.name, value: this.value}, 
        function( result ) {
            console.log('value saved');
        });
    });
});

Finally, update your ajaxConnect file:

<?php
    session_start();
    $line = isset($_POST["line"]) ? $_POST["line"] : '';
    $value = isset($_POST["value"]) ? $_POST["value"] : '';
    $_SESSION['box_'][$line] = $value;
?>