保存表单变量的onchange与阿贾克斯 [英] Saving form variables onchange with ajax
问题描述
我试图表单数据保存到 $ _ SESSION
变量使用Ajax,但我似乎无法正常运行onchange事件或发送变量。
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:
ajaxConnect:
<?php
session_start();
$_SESSION['box_']['value'] = $_POST["value"];
?>
的最终目标是为输入值保存到 $ _ SESSION ['盒子_'] ['qty_LINE']
每当值改变。
如果我设置了 $ _ SESSION
值手动,我可以得到它显示,而不是通过AJAX。
If I set the $_SESSION
value manually I can get it to show, but not through ajax.
干杯任何帮助。
推荐答案
这是一个更好的做法是使用jQuery做,而不是使用像的onchange
属性的事件绑定,而且你还需要确保你得到正确的值发送给服务器,您需要同时行名称和值。
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.
所以删除的onchange
属性:
<php
echo "<div id=\"prodBox\">QTY: <input name=\"qty_".rawurldecode($item->LINE)."\" value=\"" . $_SESSION['box_']['qty_'.rawurldecode($item->LINE)] . "\" type=\"number\" /></div>";
?>
和使用jQuery的code:
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');
});
});
});
最后,更新 ajaxConnect
文件:
<?php
session_start();
$line = isset($_POST["line"]) ? $_POST["line"] : '';
$value = isset($_POST["value"]) ? $_POST["value"] : '';
$_SESSION['box_'][$line] = $value;
?>
这篇关于保存表单变量的onchange与阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!