我正在尝试将AJAX集成到表单提交中。我目前有一种相当完善的方法来提交表单,但想摆脱整个提交,重新加载页面的事情。
我对AJAX和JQUERY完全陌生,所以学习起来很艰难。我正在努力使现有的PHP可以集成到AJAX表单提交中。我所坚持的是能够将验证结果发送到脚本的功能。
我目前在处理php的表单上有这个
已使用收到的反馈中的新代码进行更新
$return = array();
if($validation->passed()) {
try {
$getPassageId = Input::get('passageId'); //Get the passage plan id passed via the form
$latitude = convertDMSToDecimal(Input::get('lat'));
$longitude = convertDMSToDecimal(Input::get('long'));
$insertIntoWaypoints = DB::getInstance()->insert('ym_waypoints', array(
'vessel_id' => $vid,
'user_id' => $uid,
'waypoint_num' => Input::get('waypoint'),
'waypoint_name' => Input::get('waypointName'),
'latitude' => $latitude,
'longitude' => $longitude,
'cts' => Input::get('courseToSteer'),
'dtw' => Input::get('DistanceToWaypoint'),
'hw_time' => Input::get('HWTime'),
'hw_height' => Input::get('HWHeight'),
'lw_time' => Input::get('LWTime'),
'lw_height' => Input::get('LWHeight'),
'chart_num' => Input::get('chartNumbers'),
'almanac' => Input::get('almanacPages'),
'radio_signals' => Input::get('radioPages'),
'por' => Input::get('por'),
'por_almanac' => Input::get('porAlmanac'),
'por_vhf' => Input::get('porVHF'),
'vhf' => Input::get('vhf'),
'passage_note' => Input::get('notes')
));
$recordID = $insertIntoWaypoints;
$insertInto = DB::getInstance()->insert('ym_passageplan_route', array(
'passageplan_id' => $getPassageId,
'waypoint_id' => $recordID
));
$return['success'] = True;
$return['message'] = 'successful!';
print json_encode($return);
} catch (Exception $e) {
$return['success'] = False;
$return['message'] = 'fail';
print json_encode($return);
}
} else {
foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
// Append an array of the error data to $return.
$return['success'] = False;
$return['message'] .= $error;
}
print json_encode($return);
}
这是我用来发送数据的脚本
$(routePlan_form).submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/pages/voyages/passageplans/createroute.php",
dataType: 'json',
data: $("#routePlan_form").serialize(),
'success': function(data) {
if(data['success']) {
//refresh the table
$("#table").load(location.href + " #table");
//reset the form
$('#routePlan_form').trigger("reset");
//scroll to the top
window.scrollTo({ top: 0, behavior: 'smooth' });
//send the user a success message
resetToastPosition();
$.toast({
heading: 'Success',
text: 'Waypoint added successfully',
textColor: 'white',
showHideTransition: 'slide',
hideAfter : 7000,
icon: 'success',
loaderBg: '#f96868',
position: 'top-center'
})
} else {
// var i;
// for (i = 0; i < data['message'].length; i++) {
// this.error(this.xhr, data['message']);
// }
this.error(this.xhr, data['message']);
}
},
'error': function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
})
})
});
当故意提交表单时,我遗漏了必填字段,这些字段应将验证错误发送回去。在下面的出色帮助之后,我现在在控制台中得到了预期的错误。但是,它们被列为“必需的航点号。必需的航点名。必需的纬度。必需的经度。”
我需要做的是将此列表拆分为单独的消息。...
我假设我需要某种foreach或$ .each语句,但是对于JQuery来说是新手,我不确定如何进行操作...
作为一个扩展目标,我还希望将以下内容添加到整个内容中,以便可以提醒用户注意错误的字段
$("#<?php echo $field ?>").addClass("form-control-danger");
$('<label id="<?php echo $field ?>-error" class="badge badge-danger" for="<?php echo $field ?>"><?php echo $error ?></label>').insertAfter("#<?php echo $field ?>");
任何指针都很棒!
致谢
马特
快速更新---
我越来越近了!我现在在处理php文件中有以下代码
foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
// Append an array of the error data to $return.
$return['success'] = False;
$return['message'] .= [$error];
}
print json_encode($return);
以下内容将循环显示消息
else {
var i;
for (i = 0; i < data['message'].length; i++) {
this.error(this.xhr, data['message']);
}
//this.error(this.xhr, data['message']);
}
},
'error': function(jqXHR, textStatus, errorThrown) {
//send the user a success message
resetToastPosition();
$.toast({
heading: 'Error',
text: '' + textStatus,
textColor: 'white',
showHideTransition: 'slide',
hideAfter : 10000,
icon: 'error',
bgColor: '#f96868',
position: 'top-center',
loaderBg: '#405189'
})
}
这给了我5条弹出错误消息,但是文本指出ArrayArrayArrayArray,所以我知道它正在按我的预期得到4条错误。我认为发生的事情是我将错误添加到$ return ['message']数组中,因此我们正在输出a,b,c,d等。我认为我需要在'message'数组中添加一个数组??任何指向/如何获取错误消息或我要去哪里的指针?
越来越近!!
考虑到发生了什么的逻辑,我现在又变得更近了。现在,我只收到四个消息(如我期望的那样),但是所有消息都在每个消息框中分组在一起,因此我在其中添加了变量“ i”作为对“消息”部分的引用。消息,正如我所期望的!哇!
只需要弄清楚如何向字段中添加一些类,我们都很好!
我正在处理页面中编辑的零件
$return = array();
$messages = array();
$return['success'] = False;
foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
// Append an array of the error data to $return.
array_push($messages, $error);
//$return['message'] = array($error);
}
$return['message'] = $messages;
echo json_encode($return);
和表单页面上的ajax调用
$(document).ready(function() {
$(routePlan_form).submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/pages/voyages/passageplans/createroute.php",
dataType: 'json',
data: $("#routePlan_form").serialize(),
'success': function(data) {
if(data['success']) {
//refresh the table
$("#table").load(location.href + " #table");
//reset the form
$('#routePlan_form').trigger("reset");
//scroll to the top
window.scrollTo({ top: 0, behavior: 'smooth' });
//send the user a success message
resetToastPosition();
$.toast({
heading: 'Success',
text: 'Waypoint added successfully',
textColor: 'white',
showHideTransition: 'slide',
hideAfter : 7000,
icon: 'success',
loaderBg: '#f96868',
position: 'top-center'
})
} else {
var i;
for (i = 0; i < data['message'].length; i++) {
this.error(this.xhr, data['message'][i]);
}
}
},
'error': function(jqXHR, textStatus, errorThrown) {
//send the user a success message
resetToastPosition();
$.toast({
heading: 'Error',
text: '' + textStatus,
textColor: 'white',
showHideTransition: 'slide',
hideAfter : 10000,
icon: 'error',
bgColor: '#f96868',
position: 'top-center',
loaderBg: '#405189'
})
}
})
})
});
答案 0 :(得分:0)
当前看来,您似乎在每个迭代中都重新定义$return
,而不是对其进行追加:$return = array('success' => 'False');
,而不是$return["success"] = false;
。以下可能是朝正确方向迈出的一步:
<?php
// Declare an empty $return array.
$return = array();
// Iterate through the errors and populate the $return array.
foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
// Append an array of the error data to $return.
$return[] = [
"success" => false,
"message" => $error,
"field" => $field,
];
}
// Output JSON-encoded array to front-end.
echo json_encode($return);
答案 1 :(得分:0)
解决了!
我不得不在处理php中移动逻辑
if 'a' in blah.keys()
以及表单页面本身上的AJAX段
$return = array();
$messages = array();
$fields = array();
$return['success'] = False;
if($validation->passed()) {
try {
$getPassageId = Input::get('passageId'); //Get the passage plan id passed via the form
$latitude = convertDMSToDecimal(Input::get('lat'));
$longitude = convertDMSToDecimal(Input::get('long'));
$insertIntoWaypoints = DB::getInstance()->insert('ym_waypoints', array(
'vessel_id' => $vid,
'user_id' => $uid,
'waypoint_num' => Input::get('waypoint'),
'waypoint_name' => Input::get('waypointName'),
'latitude' => $latitude,
'longitude' => $longitude,
'cts' => Input::get('courseToSteer'),
'dtw' => Input::get('DistanceToWaypoint'),
'hw_time' => Input::get('HWTime'),
'hw_height' => Input::get('HWHeight'),
'lw_time' => Input::get('LWTime'),
'lw_height' => Input::get('LWHeight'),
'chart_num' => Input::get('chartNumbers'),
'almanac' => Input::get('almanacPages'),
'radio_signals' => Input::get('radioPages'),
'por' => Input::get('por'),
'por_almanac' => Input::get('porAlmanac'),
'por_vhf' => Input::get('porVHF'),
'vhf' => Input::get('vhf'),
'passage_note' => Input::get('notes')
));
$recordID = $insertIntoWaypoints;
$insertInto = DB::getInstance()->insert('ym_passageplan_route', array(
'passageplan_id' => $getPassageId,
'waypoint_id' => $recordID
));
$return['success'] = True;
$return['message'] = 'successful!';
print json_encode($return);
} catch (Exception $e) {
$return['success'] = False;
$return['message'] = 'Could't update the database';
print json_encode($return);
}
} else {
foreach (array_combine($validation->errors(), $validation->fields()) as $error => $field) {
// Append an array of the error data to $return.
array_push($messages, $error);
array_push($fields, $field);
}
$return['fields'] = $fields;
$return['message'] = $messages;
echo json_encode($return);
}
}