سؤال

I'm a beginner,so kindly help me understand this.

I have made this sample test code: (present in a external script file)

function validateForm()
{
     $.getJSON('database/grab_db.php', function(data) {
         alert("hello");
         return false;
        });
}

which is getting called from a form:

 <form id="form" action="users.php" method="post" onsubmit="return validateForm()">

Also,I have changed the content type to JSON in the php file which returns the database

header("Content-Type: application/json");

I know for a fact that the problem lies in the validateForm() method & the getJSON is not getting called properly.Tried putting alert() in validateForm(),outside of getJSON & it works well. Also,its not the case of Same Origin Policy either, as all the files are local.

Thanks in advance.

Edit:

Originally the return false; statement was outside of getJSON. But still it was not working.

هل كانت مفيدة؟

المحلول

Based on console error provided by you in the comments Uncaught ReferenceError: $ is not defined user_script.js:1 (anonymous function), it seems that you have not included jQuery library into the same file where this external script file is included.

Please included jQuery and it should work.

نصائح أخرى

validateForm doesn't have a return statement (the one in the function you pass to getJSON is a different function).

This means the function returns undefined.

This means your event handler function also returns undefined.

This doesn't stop the default action of the submit event, so the form is still submitted.

Since Ajax is asynchronous, this means the form submits before the HTTP response has come back and the callback function has run.

return false; inside the callback of $.getJSON doesn't return false for validateForm.

You could pass the form element to validateForm function like below:

html:

<form id="form" action="users.php" method="post" onsubmit="return validateForm(this);">    

js:

function validateForm(form)
{
     $.getJSON('database/grab_db.php', function(data) {
        // do some checking
        // if valid submit the form 
        form.submit(); 
     });
     // return false stop submitting the form
     return false;
}

you should go with $.ajax(); in jquery

<form id="form" action="users.php" method="post" onsubmit="return validateForm()">

Script:

function validateForm()
{
$.ajax({
type:"post",
url: "<?php echo database/grab_db.php ?>",
cache: false,
data: $("form").serialize(),
success: function(data)  // return data
{
alert(data);
}
});
return false;
}

In grab_db.php file

<?php 
$data = //fetch data

echo json_encode($data);
?>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top