</div>
</div>
<div class="grid--cell mb0 mt4">
<a href="/questions/16685126/trying-to-work-with-ajax-php" dir="ltr">Trying to work with AJAX & PHP</a>
<span class="question-originals-answer-count">
(1 answer)
</span>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2014-12-18 01:24:51Z" class="relativetime">5 years ago</span>.</div>
</div>
</aside>
I am using codeignitor for PHP app development. I was trying ajax call using jquery. But it is not working properly. When I press submit button , same form is reloaded instead of showing alert box. Your help would be very helpful. I am sharing code -
<html>
<head>
<title> My Information </title>
<script type="text/javascript" src="/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#submit').click(function(){
// alert('Btn clicked');
var form_data= {
username: $('#username').val(),
address: $('#address').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/ci-ajax/index.php/user/auth',
data: form_data,
success: function(data) {
$('body').html(data);
}
});
});
});
</script>
</head>
<body>
<form>
<label>User Name : </label>
<input type="text" name="username" id="username">
<label>Address : </label>
<input type="text" name="Address" id="address">
<input type="submit" value="Submit" name="submit" id="submit">
</form>
</body>
</HTML>
Controller
Class : user and function auth
public function auth()
{
echo "Welcome";
}
</div>
You need a way to prevent the submit action. Probably the simplest fix would be to change the input type from submit
to button
. If you want something else, you can always preventDefault
or just return false
at the end of the function.
Example with return false;
:
$('#submit').click(function() {
// alert('Btn clicked');
var form_data = {
username: $('#username').val(),
address: $('#address').val()
};
$.ajax({
type: 'POST',
url: '',
data: form_data,
success: function(data) {
$('body').html(data);
}
});
return false;
})
in your code, the form has submit input,so when click the submit ,the form will be submited to the server. So add return in $('#submit').click(function(){}. otherwise the form will submit.