Submit Ajax Form And Stay On Same Page Not Working
Solution 1:
The form submits and does not stay on the same page because of the action attribute on the form, and the normal submit button.
Which leads to your .submit()
method including .preventDefault()
probably not being interpreted after the html is loaded either.
You could do something along the lines of this:
<html>
...
<body>
...
<formid="formA"action="test.php"method="post"enctype="multipart/form-data"><inputid="commentData"name="commentData"type="text" /><inputtype="submit"value="toDb"id="toDB"name="toDB" /></form>
...
</body><script>
...script here...
</script></html>
And the javascript could be something along the lines of:
( function( $ )
{
var submit = $( 'input[id=toDB]' );
$( submit ).on
(
'click',
function( event )
{
event.preventDefault();
var form = $( this ).parent();
// Get form fieldsvar data = $( form ).serializeArray(), obj = {}, j = 0;
for( var i = 0; i < data.length; i++ )
{
if( data[i].namein obj )
{
var key = data[i].name + '_' + j;
obj[key] = data[i].value;
j++;
}
else
{
obj[data[i].name] = data[i].value;
}
};
// Make AJAX request
$.ajax
(
{
url: $( form ).attr( 'action' ),
type: 'POST',
data: 'toDB=' + JSON.stringify( obj ),
success: function( data, textStatus, xhr )
{
// Do something with data?
...
alert( 'ok' );
}
}
);
}
);
}( jQuery )
);
See the jsfiddle for yourself.
You can tell it is working because you get a console error that the request destination is not found - 404 - though the page does not refresh, you stay right where you are...with a proper page to submit to it works fully.
EDIT
I modified the setting of 'data' in the ajax()
call so that the form fields are set as a json string to a POST variable [toDB].
So in your PHP you would do:
$datas = json_decode( $_POST['toDB'], true );
And now your $datas
variable is an associative array containing all your form fields names and values. I'm not 100% on this next statement, but you may need to use PHP's stripslashes()
method on the POSTED data prior to using json_decode()
i.e.:
//Connect to database server
mysql_connect( "localhost", "user", "" ) ordie ( mysql_error() );
mysql_select_db( "test" ) ordie( mysql_error() );
$strSQL = "SELECT * FROM comments order by RAND() LIMIT 5";
$rs = mysql_query( $strSQL );
if( !$rs )
{
echo'Could not run query ' . mysql_error();
exit;
}
$dt1=date("Y-m-d");
if( isset( $_POST['toDB'] ) )
{
$datas = json_decode( stripslashes( $_POST['toDB'] ), true );
$dataA = $datas['commentData'];
$sql = "INSERT INTO comments( id, comment, datum )VALUES( DEFAULT, '" . $dataA . "', '" . $dt1 . "' );";
$result=mysql_query( $sql );
}
mysql_close();
Hope that helps
Solution 2:
Do it via form submit event
var frm = $('#formA');
frm.submit(function(e) {
//....//....
e.preventDefault();
});
And yes, sanitize DB inserts with mysql_real_escape_string($dataA)
to prevent SQL injections.
EDIT sorry, incomplete answer (still you need to use submit on form, not on document)
EDIT2 :) wrong usage of $(this) :)
$('#formA').submit(function(e) {
var formAction = $(this).attr('action');
var formData = $(this).serialize();
$.ajax({
url: formAction,
type: 'POST', // try uppercase, 'post' !== 'POST', dont know if this must be uppercase or can be lowercasedata: formData, // or try $(this).serializeArray() success: function(html) {
alert('ok');
})
});
e.preventDefault();
});
EDIT2.5: there can be problems with enctype="multipart/form-data"
you need to make some modifications:
var formData = new FormData(this);
and add some options to AJAX call
mimeType:"multipart/form-data",
contentType:false,
cache:false,
processData:false
found this page with example http://hayageek.com/jquery-ajax-form-submit/
try that UPPERCASE / lowercase POST
, and then try to remove multipart/form-data
if you dont need it (file upload etc...)
EDIT3
with multipart form, maybe you should use this in PHP in some cases to access your post data $GLOBALS['HTTP_RAW_POST_DATA']
Solution 3:
Add return false at the end of the script to prevent redirecting
Post a Comment for "Submit Ajax Form And Stay On Same Page Not Working"