简体   繁体   English

使用Jquery Ajax提交表单

[英]Submit a Form Using Jquery Ajax

Fiddle And Code: 小提琴和代码:

 $("form.signupform").submit(function(e) { var data = $(this).serialize(); var url = $(this).attr("action"); var form = $(this); // Add this line $.post(url, data, function(data) { try { data = JSON.parse(data); $(.result).html(data.result + " Watchlist"); } catch (e) { console.log("json encoding failed"); return false; } }); return false; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="result"></p> <form class="signupform" method="post" action="admin/signupinsert.php" onsubmit="this.onsubmit=function(){return false;}"> <input type="text" name="firstname" /> <input type="submit" value="Sign Up"/> </form> 

admin/signupinsert.php code: admin/signupinsert.php代码:

// Insert into DB code in PHP

$response = new \stdClass();
$response->result = "".$result."";
die(json_encode($response));

I am trying to submit this form using My Jquery Ajax Code. 我正在尝试使用“我的Jquery Ajax代码”提交此表单。 And the signupinsert.php file will return a value in $result variable. 并且signupinsert.php文件将在$ result变量中返回一个值。 I am trying to print it inside <p class="result"></p> 我正在尝试在<p class="result"></p>打印它

But, the code re-directs users to signupinsert.php page. 但是,该代码将用户重定向到signupinsert.php页面。

What's wrong? 怎么了?

you must prevent the default action of submitting the form 您必须阻止提交表单的默认操作

$("form.signupform").submit(function(e) {

    e.preventDefault(); // <-- add this

    var data = $(this).serialize();
    var url = $(this).attr("action");

also, in your php file return proper JSON and avoid parsing the response in javascript with JSON.parse(data); 另外,在您的php文件中返回正确的JSON并避免使用JSON.parse(data);解析javascript中的响应JSON.parse(data);

the output in your php file should look like this 您的php文件中的输出应如下所示

$response = new \stdClass();
$response->result = $result;

header('Content-Type: application/json');
print json_encode($response);

and in your success handler just process the data parameter as a normal json object 并在您的success处理程序中将data参数作为普通的json对象处理

$.post(url, data, function(data) { 
    $(.result).html(data.result + " Watchlist");
}

Also, just a curiosity, what is this supposed to do? 另外,出于好奇,这应该怎么办?

$response->result = "".$result."";

Update: 更新:
I just realized why you had most of the issues: 我才意识到为什么您遇到了大多数问题:

$('.result').html(data.result + " Watchlist");
  ^       ^

see the missing quotes 看到缺少的报价

you are redirecting because of action: 您由于操作而被重定向:

action="admin/signupinsert.php"
var url = $(this).attr("action");

got me? 抓到我了吗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM