I have seen many posts but still not able to figure out why this code is not working. I have a user_dashboard.html which contains the code:-
<script>
$(document).ready(function (e) {
//e.preventDefault();
$('#search_button').click( function() {
$.get("db_test2.php", function(data, status) {
console.log("Test Log");
alert("Data:"+data+"
Status:"+status);
});
});
});
</script>
The db_test2.php is a file present in the same folder and contains the code:-
<?php
echo "This is a db test";
?>
The problem is that I am not getting any alert and no console logs are being generated.
You have a submit button, so by default after running your click handler, it will submit the form immediately. To prevent this, you can return false
or e.preventDefault()
:
$('#search_button').click( function() {
$.get("db_test2.php", function(data, status) {
console.log("Test Log");
alert("Data:"+data+"
Status:"+status);
});
return false; // stop the form being submitted
});
Just to make sure, put a console.log("clicked");
to make sure the method is being called
$('#search_button').click( function() {
console.log("clicked"); // here
$.get("db_test2.php", function(data, status) {
console.log("Test Log");
alert("Data:"+data+"
Status:"+status);
});
});
EDIT
Works fine on my JSFiddle
If db_test2.php
is within the same directory as the file you're in, try putting the whole url
e.g. www.domain.co.uk/directory/db_test2.php
if it works then you know that is it not finding db_test2.php
and that is where your issue is.
Also, are there any errors in your console?
I would insert the following alerts earlier in the code, to try and track the problem:
<script>
$(document).ready(function (e) {
alert('#search_button').length);//to confirm the presence of the button
$('#search_button').click( function() {
alert('Button clicked!');
$.get("db_test2.php", function(data, status) {
console.log("Test Log");
alert("Data:"+data+"
Status:"+status);
});
});
});
</script>
So, apart from your "Test Log", I assume there's no other Javascript error on the console? And finally, reconfirm that your 'db_test2.php' is indeed where you thought it was, 'cause a 404 error can often cause this kind of silent, frustrating error!