javascript - Submit ajax form and stay on same page not working -


i want store comments users in databse. when user submits don't want redirect them new page. have following code it's not working.

my html code:

<form id="forma" action="test.php" method="post" enctype="multipart/form-data"> <input id="commentdata" name="commentdata" type="text" >' <input type="submit" value="todb" id="todb" name="todb" /></form> 

javascript:

var frm = $('#forma');  $(document).submit(function(e) { e.preventdefault();  $.ajax({      url: frm.attr('action'),      type: frm.attr('method'),      data: frm.serialize(),      success: function(html) {          alert('ok');      }  }); }); 

here php file:

//connect database server mysql_connect("localhost", "user", "") or die (mysql_error ()); mysql_select_db("test") or die(mysql_error()); $strsql = "select * comments order 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'])){   $dataa = $_post['commentdata'];   $sql = "insert comments(id, comment, datum)values(default,'$dataa', '$dt1')";   $result=mysql_query($sql); } mysql_close(); 

when click on submit button stay on same page , show alert data of input field not inserted in database. when remove e.preventdefault() data goes database page redirects test.php

tried different things can't figure out. can me out? in advance!

the form submits , not stay on same page because of action attribute on form, , normal submit button.

which leads .submit() method including .preventdefault() not being interpreted after html loaded either.

you along lines of this:

<html>   ...   <body>   ...     <form id="forma" action="test.php" method="post" enctype="multipart/form-data">       <input id="commentdata" name="commentdata" type="text" />       <input type="submit" value="todb" id="todb" name="todb" />     </form>   ...   </body>   <script>    ...script here...   </script>  </html> 

and javascript along lines of:

( function( $ )   {     var submit = $( 'input[id=todb]' );     $( submit ).on     (       'click',       function( event )       {         event.preventdefault();         var form = $( ).parent();          // form fields         var data = $( form ).serializearray(), obj = {}, j = 0;         for( var = 0; < data.length; i++ )         {           if( data[i].name in 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 )             {               // data?               ...                   alert( 'ok' );                 }           }         );       }     );   }( jquery ) ); 

see jsfiddle yourself.

you can tell working because console error request destination not found - 404 - though page not refresh, stay right are...with proper page submit works fully.

edit

i modified setting of 'data' in ajax() call form fields set json string post variable [todb].

so in php do:

$datas = json_decode( $_post['todb'], true ); 

and $datas variable associative array containing form fields names , values. i'm not 100% on next statement, may need use php's stripslashes() method on posted data prior using json_decode()

i.e.:

//connect database server mysql_connect( "localhost", "user", "" ) or die ( mysql_error() ); mysql_select_db( "test" ) or die( mysql_error() ); $strsql = "select * comments order 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 comments( id, comment, datum )values( default, '" . $dataa . "', '" . $dt1 . "' );";   $result=mysql_query( $sql ); } mysql_close(); 

hope helps


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -