使用ajax将注释插入数据库

时间:2015-03-01 04:38:56

标签: php jquery html ajax

我知道在这个帖子中已经多次提到过,但我仍然无法弄清楚如何解决我的问题。我在如何从comment.php发送和获取我的数据到insert.php

时遇到了困难

这是我的评论代码.php:

(请注意javascript中方法部分的评论[其中有三个],我已经尝试过将它们插入到数据库中但是无济于事他们没有用。我还是毕竟学习。)有人可以帮助我。我还是初学者,所以我可能会发现很难理解进步,但我会尽我所能。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Comment</title>

<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="bootstrap.min" />


<script type = "text/javascript" >
<!-- method 1-->
//$(document).ready( function() {
//  $('#submit').click( function() {
//  
//      $('#getResponse').html('<img src="bootstrap/images    /loading.gif">');
//      $.post( 'insert.php', function(sendRequest) {
//      var xmlhttp = new XMLHttpRequest();
//  xmlhttp.onreadystatechange = function()
//  (
//      if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
//      (
//          document.getElementbyId("getResponse").innerHTML =     xmlhttp.responseText;
//      )
//  )
//       xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+"    &email="+document.getElementbyId("email").value+"&web="+document.getElementbyId("url").value+"&    comment="+document.getElementbyId("body").value+,true);
//  xmlhttp.send();
//              $('#getResponse').html(sendRequest);

//      });
//  });


//});

<!-- -->

<!-- method 2-->

//function sendRequest() (
//  var xmlhttp = new XMLHttpRequest();
//  xmlhttp.onreadystatechange = function()
//  (
//      if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
//      (
//          document.getElementbyId("getResponse").innerHTML =     xmlhttp.responseText;
//      )
//  )
//          xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+"    &email="+document.getElementbyId("email").value+"&    web="+document.getElementbyId("url").value+"&    comment="+document.getElementbyId("body").value+,true);
//  xmlhttp.send();
//)

<!-- -->


<!-- method 3-->

// function sendRequest()
//{
//  var xmlhttp = new XMLHttpRequest();
//      xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+"    &email="+document.getElementbyId("email").value+"&    web="+document.getElementbyId("url").value+"&        comment="+document.getElementbyId("body").value+,false);
//  xmlhttp.send(null);

//  document.getElementbyId("getResponse").innerHTML =     xmlhttp.responseText;
//}

<!-- -->
</script>

</head>

<body>



<form method = "post" action="">

<div id="main">





<div class="comment" style="display: block;">
            <div class="avatar">

                <img src="img/default_avatar.gif">

            </div>

            <div class="name">Avatar</div>
            <div class="date" title="Added at 02:24 on 20 Feb 2015">20     Feb 2015</div>
            <p>Avatar</p>
</div>

                <div id="addCommentContainer">
                <p>Add a Comment</p>

    <form id="addCommentForm" method="Get" action="">
        <div>
            <label for="name">Your Name</label>
            <input type="text" name="name" id="name">

            <label for="email">Your Email</label>
            <input type="text" name="email" id="email">

            <label for="url">Website (not required)</label>
            <input type="text" name="url" id="url">

            <label for="body">Comment Body</label>
            <textarea name="body" id="body" cols="20" rows="5">    </textarea>

            <input type="submit" name="submit" id="submit" value="Submit" >
        </div>
    </form>

    <div id = "getResponse"></div>
</div>


</div>

</form>

</body>
</html>

这是我的php.php我的php文件的代码,我在其中执行数据插入数据库。

<?php

mysql_connect("localhost","root");
mysql_select_db("comment");

   $name = $_GET['name'];
   $email = $_GET['email'];
   $web = $_GET['web'];
   $comment = $_GET['comment'];

   mysql_query("INSERT INTO demo (c_name,c_email,c_web,c_comment) VALUES     ('$name','$email','$web','$comment')");

   echo "Inserted Successfully";

   ?>

3 个答案:

答案 0 :(得分:0)

在comment.php文件中,使用Button,而不是提交。

在该按钮的click事件中,调用jQuery ajax

$('#button_id').click(function(){
   //Get values of input fields from DOM structure 
   var params,name,email,url,body;
   name=$("#name").val();
   email=$("#email").val();
   url=$("#url").val();
   body=$("#body").val(); 

   params = {'name':name,'email':email,'web':url,'comment':body};

   $.ajax({
   url:'insert.php',  
   data:params,
   success:function(){
     alert("hello , your comment is added successfully , now play soccer :) !!");
   }
   });
});

<强>更新

我不知道你是使用按钮还是提交。所以我指的是你。

<input type="button" name="submit" id="button_id" value="Submit" >

答案 1 :(得分:0)

你也可以使用表格序列化功能,这是一种很好的方法。

$('#addCommentForm').submit(function(form){ 
   $.ajax({
      url:'insert.php',  
      data: $(form).serialize(),
      success:function(){
          alert("hello , your comment is added successfully , now play soccer :) !!");
      }
   });
}); 

答案 2 :(得分:0)

  

你可以用这个来提交记录到insert.php动作的形式应该是action =“insert.php”

$('form#addCommentForm').on('submit', function(){
	 $("#response").show();
	var that = $(this),
	url = that.attr('action'),
	type = that.attr('method'),
	data = {};
	
	that.find('[name]').each(function(index, value ){
		 $('#response').html('<img src="images/loadingbar.gif"> loading...');
    		var that = $(this),
			name = that.attr('name'),
			value = that.val();
		data[name] = value;
		
	});	
	$.ajax({
		url: url,
		type: type,
		data: data,
		success: function(response) {
			console.log(response);
			$(".ajax")[0].reset();
			$("#response").hide();
		}
	});
	return false;	
});

  

形成数据库连接脚本使用此

<?php 
	$connect_error = 'sorry we\'re experiencing connection problems';
	mysql_connect('localhost', 'root', '') or die($connect_error) ;
	mysql_select_db('comment') or die($connect_error);
?>