[英]Submit form with AJAX and send data to file as JSON
我一直試圖弄清楚這一點。 我想提交一個表單並將其數據作為 JSON 存儲在一個文件中。 我必須找到解決方案的一部分,使用PHP將數據存儲到文件中,但現在我想避免在提交表單后重定向。
HTML
<form action="saveit.php" method="POST">
<div class="form-group" id="vaga-group">
<label for="vaga">Job</label>
<input type="text" class="form-control" id="vaga" name="vaga" placeholder="Ex.: UX Designer, Desenvolvedor Java">
</div>
<div class="form-group" id="cidade-group">
<label for="cidade">City</label>
<input type="text" class="form-control" id="cidade" name="cidade" placeholder="Ex. São Paulo">
</div>
<div class="form-group" id="tipo-group">
<label for="tipo">Type</label>
<select class="form-control" name="tipo" id="tipo">
<option>Full time</option>
<option>Freelance</option>
</select>
</div>
<button class="btn btn-primary" type="submit">Send</button>
</form>
保存.php
<?php
$filetxt = 'js/list.json';
$formdata = array(
'vaga'=> $_POST['vaga'],
'cidade'=> $_POST['cidade'],
'tipo'=> $_POST['tipo']
);
$arr_data = array();
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
$arr_data[] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('js/list.json', $jsondata);
$form_state['redirect'] = false;
?>
通過完全提交現在我的list.json文件更新了新信息,如下所示:
[
{
"vaga": "Desenvolvedor Front-End",
"cidade": "New York",
"tipo": "Freelance"
},
{
"vaga": "Desenvolvedor Java",
"cidade": "Chicago",
"tipo": "Freelance"
}
]
現在我想在提交表單后使用 AJAX 停止重定向。 我知道因為我正在使用action="saveit.php"它正在重定向到該文件(或我在該文件中指出的任何地方),但是我沒有找到正確使用 AJAX 來驗證和提交沒有重定向的表單。
我發現了大量的 AJAX 代碼示例來停止重定向,但沒有一個讓我在提交后繼續將新數據存儲到 list.json 中,這就是問題所在。 請幫忙! 謝謝!
擺脫表單action
使用 jQuery(或者 XMLHTTPRequest,如果你覺得大膽的話)
(將其彈出到<script>
標簽中)
function ajaxSubmit(){
$.post('saveit.php', {
vaga: document.getElementById('vaga').value, // all the values you
cidade: document.getElementById('cidade').value, // want to send
// and so on ...
}).done(function(result){
// result = server result
// do what you must to notify client here
}).fail(function(err){
// oh dear ... error. tell user
})
}
button
<button class="btn btn-primary" onclick='ajaxSubmit()'>Send</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.