Jump to content

Please look at this code and see what I am doing wrong. It's about adding and displaying a record using PHP , Mysql and ajax.


man5

Recommended Posts

All I am trying to do is add a record on a page without the page refreshing.  For that ajax is used.  Here is the code.

 

It does not add the record to mysql table. Can anyone tell me what I am doing wrong?

 

 

record.php

<!DOCTYPE HTML>
<html lang="en"> 
	<head>
		<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
		<script type="text/javascript" >
			$(function() {
				$(".submit_button").click(function() {
					var textcontent = $("#content").val();
					var name = $("#name").val();
					var dataString = 'content='+ textcontent + '&name='+name;
					if(textcontent=='')
					{
						alert("Enter some text..");
						$("#content").focus();
					}
					else
					{
						$("#flash").show();
						$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
						$.ajax({
							type: "POST",
							url: "action.php",
							data: dataString,
							cache: true,
							success: function(html){
								$("#show").after(html);
								document.getElementById('content').value='';
								$("#flash").hide();
								$("#content").focus();
							}  
						});
					}
					return false;
				});
			});
		</script>
	</head>
	<body>
	<?php
		$record_id = $_GET['id']; // getting ID of current page record 
	?>
	
		<form action="" method="post" enctype="multipart/form-data">
			<div class="field">
				<label for="title">Name *</label>
				<input type="text" name="name" id="name" value="" maxlength="20" placeholder="Your name">
			</div>
			<div class="field">
				<label for="content">content *</label>
				<textarea id="content" name="content" maxlength="500" placeholder="Details..."></textarea>
			</div>
			<input type="submit" name="submit" value="submit" class="submit_button">
		</form>
		<div id="flash"></div>
		<div id="show"></div>
		
	</body>
</html>	

action.php

if(isset($_POST['submit'])) {
	if(empty($_POST['name']) || empty($_POST['content'])) {
		
		$error = 'Please fill in the required fields!';
		
	} else {
		try {
			
			$name		= 	trim($_POST['name']);
			$content 	= 	trim($_POST['content']);
					
			$stmt = $db->prepare("INSERT INTO records(record_id, name, content) 
				VALUES(:recordid, :name, :content");
			$stmt->execute(array(
				'recordid'		=> $record_id,
				'name'			=> $name,
				'content' 		=> $content
			));
			
			if(!$stmt){
			
				$error = 'Please fill in the required fields.';
				
			} else {
			
				$success = 'Your post has been submitted.';
			
			}
			
		} catch(Exception $e) {
			die($e->getMessage());
		}
	}
}
Link to comment
Share on other sites

And a third thing,

if(!$stmt){
will never be true.

 

Can you please elaborate? I do not understand what you are trying to say.  Thanks.

$stmt->execute(array(
	'recordid'		=> $record_id,
	'name'			=> $name,
	'content' 		=> $content
));
The array to execute() uses names like "recordid" but it needs to match exactly the placeholder used in the prepared statement,

$stmt = $db->prepare("INSERT INTO records(record_id, name, content) 
	VALUES(:recordid, :name, :content");
so that means it should be like ":recordid" instead. Edited by requinix
Link to comment
Share on other sites

And a third thing,

if(!$stmt){
will never be true.

 

$stmt->execute(array(
	'recordid'		=> $record_id,
	'name'			=> $name,
	'content' 		=> $content
));
The array to execute() uses names like "recordid" but it needs to match exactly the placeholder used in the prepared statement,

$stmt = $db->prepare("INSERT INTO records(record_id, name, content) 
	VALUES(:recordid, :name, :content");
so that means it should be like ":recordid" instead.

 

 

 

I should mention that there is nothing wrong with my prepared statements. They work perfectly with the database insertion.  The issue I am having is when I add the ajax/js code and then it doesn't work. 

 

Would it be possible for you to fix my code/setup and re-post so that I can see exactly where I went wrong?

Link to comment
Share on other sites

i've actually seen it work where the named place-holder in the query statement has a : as part of the name, but the bind/execute() reference doesn't.

I've always suspected that but never seen it done before in reference-quality material (documentation, tutorials, etc).
Link to comment
Share on other sites

your php code may have worked before adding the ajax, but that doesn't mean it was correct.

 

someone posted why your ajax code isn't causing the php code to run. i recommend reviewing all the replies in the thread.

 

 

Here is the fixed php code.

 

action.php

if(isset($_POST['submit'])) {
	if(empty($_POST['name']) || empty($_POST['content'])) {
		
		$error = 'Please fill in the required fields!';
		
	} else {
		try {
			
			$name		= 	trim($_POST['name']);
			$content 	= 	trim($_POST['content']);
					
			$stmt = $db->prepare("INSERT INTO records(record_id, name, content) 
				VALUES(:record_id, :name, :content");
			
			$stmt->bindParam('record_id', $record_id);
			$stmt->bindParam('name', $name);
			$stmt->bindParam('content', $content);
			$stmt->execute();
			
			if($stmt == false){
			
				$error = 'Please fill in the required fields.';
				
			} else {
			
				$success = 'Your post has been submitted.';
			
			}
			
		} catch(Exception $e) {
			die($e->getMessage());
		}
	}
}

As for the ajax, I suspect I am doing more than 1 thing wrong.  I can never get it work. If you can edit my code, that way I can SEE what I did wrong.  Or I can keep spending more hours on it and get no where.

Link to comment
Share on other sites

no one is going to type up fixed code for you as that won't help you to learn how to program or learn how to troubleshoot problems in your code. learning the meaning of what you are doing is required in order to program, so that you can take concepts and information you learned in one context and apply them in another context.

 

your php code is expecting three input variables - $_POST['submit'], $_POST['name'], and $_POST['content']. before you added ajax to your code, your form was submitting those three variables. your ajax code must therefore submit the same variables. this is your line of javascript that's producing the data that's being submitted - var dataString = 'content='+ textcontent + '&name='+name;. your task would be to make sure there is a 'submit' value in that.

Link to comment
Share on other sites

no one is going to type up fixed code for you as that won't help you to learn how to program or learn how to troubleshoot problems in your code. learning the meaning of what you are doing is required in order to program, so that you can take concepts and information you learned in one context and apply them in another context.

 

your php code is expecting three input variables - $_POST['submit'], $_POST['name'], and $_POST['content']. before you added ajax to your code, your form was submitting those three variables. your ajax code must therefore submit the same variables. this is your line of javascript that's producing the data that's being submitted - var dataString = 'content='+ textcontent + '&name='+name;. your task would be to make sure there is a 'submit' value in that.

 

 

I understand what you are saying but you have to realize that until I see the correct solution, I am going to be running in circles. I am not as good with js/ajax as I am with PHP.  

 

Here is the updated ajax code with what you mentioned. I get no errors in the console but still it shows up blank after i press submit.

<!DOCTYPE HTML>
<html lang="en"> 
	<head>
		<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
		<script type="text/javascript" >
			$(function() {
				$(".submit_button").click(function() {
                                       var submit = $("#submit").val();
					var textcontent = $("#content").val();
					var name = $("#name").val();
					var dataString = 'submit='+ submit + 'content='+ textcontent + '&name='+name;
					if(textcontent=='')
					{
						alert("Enter some text..");
						$("#content").focus();
					}
					else
					{
						$("#flash").show();
						$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
						$.ajax({
							type: "POST",
							url: "action.php",
							data: dataString,
							cache: true,
							success: function(html){
								$("#show").after(html);
								document.getElementById('content').value='';
								$("#flash").hide();
								$("#content").focus();
							}  
						});
					}
					return false;
				});
			});
		</script>
	</head>
	<body>
	<?php
		$record_id = $_GET['id']; // getting ID of current page record 
	?>
	
		<form action="" method="post" enctype="multipart/form-data">
			<div class="field">
				<label for="title">Name *</label>
				<input type="text" name="name" id="name" value="" maxlength="20" placeholder="Your name">
			</div>
			<div class="field">
				<label for="content">content *</label>
				<textarea id="content" name="content" maxlength="500" placeholder="Details..."></textarea>
			</div>
			<input type="submit" name="submit" value="submit" class="submit_button" id="submit">
		</form>
		<div id="flash"></div>
		<div id="show"></div>
		
	</body>
</html>	
Link to comment
Share on other sites

Spend some time learning how to debug JavaScript in the browser:

 

Generic: http://juliepagano.com/blog/2014/05/18/javascript-debugging-for-beginners/

Chrome: https://developer.chrome.com/devtools/docs/javascript-debugging

Firefox: https://developer.mozilla.org/en-US/docs/Debugging_JavaScript

 

Then, check the value of dataString to see if it's a valid query string.

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.