fello
fello

Reputation: 339

need help submiting this form with jquery... It is submiting but the whole browser is refreshing

 $idc = $_GET['id'];
    $name1 = $_GET['name'];
    $id2 = $_GET['ids'];
     if ($_POST['message_field'] != ""){
        $message_field = $_POST['message_field'];

          $sql = mysql_query("INSERT INTO comment (mem_id,commented_men_id, message, message_date) 
         VALUES('$userid','$idc','$message_field', now())")  
         or die (mysql_error());

    }

        $sql_message = mysql_query("SELECT id, mem_id ,message, message_date FROM comment WHERE mem_id='$userid'  ORDER BY message_date DESC");

        while($row = mysql_fetch_array($sql_message)){


            $id = $row["id"];
            $me_id = $row["mem_id"];
            $json = $row["message"];
                 $message_date = $row["message_date"];
                $message = json_encode($json);

 $sql_mem_data = mysql_query("SELECT id, name FROM users WHERE  id='$me_id'");
              while($row2 = mysql_fetch_array($sql_mem_data)){
                $id = $row2["id"];
                $ufirstname = $row2["name"];
        }

    $messageList .= '<div id="only"><p>' . ufirstname . '</p><br/><p    id="pmessage">'.$the_message.'</p></div>';

    }

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title> Book</title>
    <link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="jquery.form.js"></script>
    <script type="text/javascript" src="mootools-core-1.3.2-full-compat.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){

       $("#messageinput").click(function() {
           $.post($('#message').attr("action"),
                  $("#message").serialize(),
                  function(html) {
                    var comment = $(html) .find('#messageoutput').html();
                      $("#pmessage").html(comment);
              });
   });
       });

    </script>
         <div id="messageid">
             <form align="left" id="message" action="<?php profile.php?id='.$idc.'& ids='.    $id2.'&name='.$name1.'?>" method="post" enctype="multipart/form-data" name="blab_from">
        <textarea name="message_field" rows="3" style="width:97%;"></textarea>
         <input id="messageinput" name="submit" type="button" value="submit" align="left" />
        </form>
        </div>
        <div id="messageoutput"><?php print "$messageList"; ?></div>

Upvotes: 2

Views: 752

Answers (4)

LoneWOLFs
LoneWOLFs

Reputation: 2306

You can do it like this... Suppose this is your html

<form align="left" id="form1" action="" method="post"   enctype="multipart/form-data" name="message_from">
<textarea id="message_field" name="message_field" rows="3" style="width:97%;"></textarea>
<input id="messageinput" name="submit" type="button" value="Submit" align="left" />
</form>
<div id="result"></div>

Then the following code will submit the form data and will echo the result back in the 'data' variable. You can do whatever you want to do with the return data then. Like in the example i am putting the returned data in a div with id="result".

$(document).ready(function(){
    $("#messageinput").click(function(){
        $.post('html.php',$("#form1").serialize(),function(data){
            $("#result").html(data);
        });

    });
});

Solution to your modified script

<?php
//engine.php
//for convinence sake split the php and html into 2 files say php is in engine.php and html in profile.php
//why are you using &name and &ids for? my best guess is u need only &id and &message_field if its a msg post

//this file will do 2 things when id is passed return the comments and when id and message is passed insert the comment into db fetch it again and pass it.
//the html manipulation will be done by jQuery/javascript only you dont need php for that

//  $idc = $_GET['id'];
//  $name1 = $_GET['name'];
//  $id2 = $_GET['ids'];

    $idc = $_POST['id'];//[we are using post so use _POST methods]


    if ($_POST['message_field'] != "")
    {
        //here you are missing connection statements like mysql_connect() and mysql_select_db()
        $message_field = $_POST['message_field'];
        $sql = mysql_query("INSERT INTO comment (mem_id,commented_men_id, message, message_date)VALUES('$userid','$idc','$message_field', now())") or die (mysql_error());  
    }

    $sql_message = mysql_query("SELECT id, mem_id ,message, message_date FROM comment WHERE mem_id='$userid'  ORDER BY message_date DESC");

    $i = 0;
    $messageList = '<div id="result">';
    while($row = mysql_fetch_array($sql_message))
    {
        $j=$i++;
        $id = $row["id"];
        $me_id = $row["mem_id"];        
        $message_date = $row["message_date"];
        //$json = $row["message"];
        //$message = json_encode($json);
        $message = $row["message"]; //disabling json for now

        $sql_mem_data = mysql_query("SELECT id, name FROM users WHERE  id='$me_id'");

        while($row2 = mysql_fetch_array($sql_mem_data))
        {
            $id = $row2["id"];
            $ufirstname = $row2["name"];
        }
        //$messageList .= '<div id="only"><p>' . ufirstname . '</p><br/><p    id="pmessage">'.$the_message.'</p></div>'; //[error 1] ur writting this outside while loop also id="only" multiple times will create error same with id="pmessage"
        /*[error 1] rectification*/ $messageList .= '<div id="row_'.$j.'"><p id="uname_'.$j.'">'.$ufirstname.'</p><br/><p id="msg_'.$j.'">'.$message.'</p></div>';
    }
    $messageList .= '</div>'; //making id="result" parent of all the rows
    echo $messageList; //script has to echo for jQuery to catch it.
?>
<!--This file is profile.php(assumption)-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Book</title>
<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript" src="mootools-core-1.3.2-full-compat.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/*i still didn't get why you use $id2 and &name2 but the above php block is used to only fetch data which is passed by the javascript
so you need 2 events first when the page is loaded and 2nd when the page is posted with a new comment
*/
(function($)
{
    $.getParam = function(key)
    {
        var urlParams = decodeURI( window.location.search.substring(1) );
        if(urlParams == false | urlParams == '') return null;
        var pairs = urlParams.split("&");

        var keyValue_Collection = {};
        for(var value in pairs)
        {
            var equalsignPosition = pairs[value].indexOf("=");
            if (equalsignPosition == -1) 
                keyValue_Collection[ pairs[value] ] = ''; 
            else
                keyValue_Collection[ pairs[value].substring(0, equalsignPosition) ] = pairs[value].substr(equalsignPosition + 1);
        }
        return keyValue_Collection[key];
    }
})
(jQuery);

//fetch the id to get the messages
var id = $.getParam("id");

//if its a click
$("#messageinput").live('click',function(){
    var msg = $("#message_field").val();
    var qstring='id='+id+'&message_field='+ msg;
    $.post('engine.php',qstring,function(data){
        $("#messageoutput").html(data);//bind the whole data to messageoutput div as its already formatted for right html
    });
});

//else load default messages
var qstring = 'id='+id;
$.post('engine.php',qstring,function(){
    $("#messageoutput").html(data);//in this php script will return only the messages for the passed id.
});

});
</script>
<div id="messageid">
    <form align="left" id="message" action="" method="post" enctype="multipart/form-data" name="blab_from">
    <textarea id="message_field" name="message_field" rows="3" style="width:97%;"></textarea>
    <input id="messageinput" name="submit" type="button" value="submit" align="left" />
    </form>
</div>
<!--<div id="messageoutput"><?php/* print "$messageList"; */?></div>--> <!--This is not needed when u do it by AJAX simply put an empty div for results-->
<div id="messageoutput"></div>

Upvotes: 3

addedlovely
addedlovely

Reputation: 3194

Use the submit event on the form rather than click.

$('#submit).submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

Upvotes: 0

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17586

i think you cannot submit a form with out refreshing the page using type="submit". instead use type="submit" use type="button"

Upvotes: 0

Karthik
Karthik

Reputation: 522

Use type="button" instead of type="submit" in input tag. Because submit button will submit the form and refresh the page.

Upvotes: 1

Related Questions