javascript - Success in $.ajax is not get executed -
i novice ajax. first example, wanted implement add operation. purpose, wrote following code:
html:
<!doctype html> <html> <head> <title>add 2 numbers</title> <meta content="text/html;charset=utf-8" http-equiv="content-type"> <meta content="utf-8" http-equiv="encoding"> <script src="jquery.js"></script> </head> <body> <form id="addform" method="post"> <input type="text" name="first"> <input type="text" name="second"> <input type="submit" name="btnsubmit"> </form> <script src="global.js"></script> </body> </html>
php:
<?php header('content-type: text/html; charset=utf-8'); $json = array('success' => false, 'result' => 1 ); if (isset($_post['first']) && isset($_post['second'])) { $json['success'] = "true"; $first = $_post['first']; $second = $_post['second']; $json['result'] = $first + $second; } echo json_encode($json); ?>
global.js
$('#addform').on('submit', function () { // alert("hello submit"); var contents = $(this).serialize(); $.ajax( { url:'add.php', datatype: 'json', type:'post', data:contents, success:function(data) { if(data.success) { alert("result " + data.result); } } } ); // alert("wfah"); });
the problem when uncomment // alert("wfah"); , result in ajax success , redirect add.php. when don't uncomment it, directly redirected add.php. seems success not called. please me. suggest source learn ajax. thank you.
$('#addform').on('submit', function (e) { e.preventdefault(); //<----- need prevent form submitting // alert("hello submit"); var contents = $(this).serialize(); $.ajax( { url:'add.php', datatype: 'json', type:'post', data:contents, success:function(data) { if(data.success) { alert("result " + data.result); } } } ); // alert("wfah"); });
Comments
Post a Comment