Jump to content

Small issue inserting and retrieving a row with php and ajax


helloworld001
Go to solution Solved by helloworld001,

Recommended Posts

Below is my code that is suppose to insert and show records from database using ajax. 

 

Retrieving the records from the database works.  However it won't insert a record.  I do not get any errors. The page simply refreshes when I hit submit button.

 

Can you see what might be wrong in my code?

 

 

index.php

<script>
	$(document).ready(function(){
		function showComment(){
		  $.ajax({
			type:"post",
			url:"process.php",
			data:"action=showcomment",
			success:function(data){
				 $(".wrapper").html(data);
			}
		  });
		}

		showComment();


		$("#submit").click(function(){

			  var name=$("#name").val();
			  var message=$("#details").val();

			  $.ajax({
				  type:"post",
				  url:"process.php",
				  data:"name="+name+"&details="+message+"&action=addcomment",
				  success:function(data){
					showComment();
					  
				  }

			  });

		});
   });
   </script>

$id      =     $_GET['id'];
$title    =    $_GET['title'];
        
$_SESSION['id']      =    $id;
$_SESSION['title']   =    $title;

<div class="wrapper"></div>

<form action="" method="post" enctype="multipart/form-data">
    <div class="newfield">
        <label for="title">Name <span class="highlight">*</span></label>
        <input id="name" type="text" name="name">
    </div>
    <div class="newfield">
        <label for="details">Details <span class="highlight">*</span></label>
        <textarea id="details" name="details""></textarea>
    </div>
    <input type="submit" name="submit" id="submit" value="Submit Tale">
</form>


process.php

<?php require_once '/core/init.php';

$id 	= 	$_SESSION['id'];
		
$action = $_POST['action'];

if($action == 'showcomment') {

	try {
		$get = $db->prepare("SELECT * FROM sub_posts WHERE id = :id");
		$get->bindParam('id', $id);
		$get->execute();
		$getStmt = $get->fetchAll(PDO::FETCH_ASSOC);
		if(count($getStmt) > 0) {
			
			foreach($getStmt as $row) {
			
				$new_name		= 	$row['name'];
				$new_details	= 	$row['details'];
				
				?>	
					<ul>
						<li>
							<?php echo $new_name; ?>
						</li>
						<li>
							<?php echo $new_details; ?>
						</li>
					</ul>
				<?php 
			}	
			
		} else {

			// no records found.
			
		}
		
	} catch(Exception $e) {
		die($e->getMessage());
	}

} else if($action == 'addcomment') {
								
	$name		= 	$_GET['name'];
	$details	= 	$_GET['details'];
			
	
		try {
			
			$insert = $db->prepare("INSERT INTO sub_posts(id, name, details) VALUES(:id, :name, :details)");
			$insert->bindParam('id', $id);
			$insert->bindParam('name', $name);
			$insert->bindParam('details', $details);
			$insert->execute();
			
			if($insert == false){
				
				echo 'record could not be inserted.';
				
			} else {
			
				echo 'record has been inserted.';
			
			}
			
		} catch(Exception $e) {
			die($e->getMessage());
		}
	

} else {

	echo 'no results.';
}
Edited by helloworld001
Link to comment
Share on other sites

have you set the PDO error mode so that an error will throw an exception?

 

id's in database tables are generally defined to be unique and trying to insert more than one row with the same id value could be (depending on your table definition) throwing an error.

 

btw - in your ajax code, you need to prevent the default form action so that the form won't submit a second time.

Link to comment
Share on other sites

  • Solution

have you set the PDO error mode so that an error will throw an exception?

 

id's in database tables are generally defined to be unique and trying to insert more than one row with the same id value could be (depending on your table definition) throwing an error.

 

btw - in your ajax code, you need to prevent the default form action so that the form won't submit a second time.

 

 

I have solved the issue.  

 

I did add "ev.preventDefault();" into the ajax code.  But the real problem was that I had to change the ' Input type="submit" ' to ' Input type="button" '.  Now it works like a charm.

 

Also in my original code, It's $_POST and not $_GET for the name and details variables.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.