Jump to content

Quick question. Is it possible to load html data via ajax, into to individual div element?


helloworld001
Go to solution Solved by maxxd,

Recommended Posts

For eg, say I am retreiving 3 records from database and they look like this.

<div class="record">
   <h1>Record title 1</h1>
   <p>Record description</p>
   <button class="button">send message</button> 
</div>

<div class="record">
   <h1>Record title 2</h1>
   <p>Record description</p>
   <button class="button">send message</button> 
</div>

<div class="record">
   <h1>Record title 3</h1>
   <p>Record description</p>
   <button class="button">send message</button> 
</div>

and this is my ajax to load the form.

		<script>
			$(document).ready(function(){
				$(".button").click(function(){
					$(".record").load("form.php .new-form");
				});
			});
		</script>

the form looks like this.

<form class="new-form">
	<textarea name="message" class="message"></textarea>
	<input type="button" name="submit" class="form-submit" value="Send Message">
</form>

That all works.  The only problem with that is, it loads the form in EACH record.  How can I make it so that the form only loads to the div record from which I am calling  from?

Link to comment
Share on other sites

To make it more clear, when I press the ".button", it will load the "form" in "#record" container. Like this.

<div class="record">
   <h1>Record title 3</h1>
   <p>Record description</p>
   <button class="button">send message</button> 

   <form class="new-form">
       <textarea name="message" class="message"></textarea>
       <input type="button" name="submit" class="form-submit" value="Send Message">
   </form>
</div>

From that point on, I will be using ajax to submit that message. But again the issue is that the form loads in ALL the ".record" containers at the same time when I press only ONE ".button". I just like to make it so that it's unique to each container.

Edited by helloworld001
Link to comment
Share on other sites

You can try to get the parent div of the button that was clicked.

$(".button").click(function(){
  $(this).parent('div').load("form.php .new-form");
});

Not sure what the ".new-form" stuff is in your jQuery.load() function though...

 

Here's a quick jsfiddle to show it will target the correct div by changing the background color of the div where the button was clicked

http://jsfiddle.net/x276emhc/

Edited by CroNiX
  • Like 1
Link to comment
Share on other sites

You can try to get the parent div of the button that was clicked.

$(".button").click(function(){
  $(this).parent('div').load("form.php .new-form");
});

Not sure what the ".new-form" stuff is in your jQuery.load() function though...

 

Here's a quick jsfiddle to show it will target the correct div by changing the background color of the div where the button was clicked

http://jsfiddle.net/x276emhc/

 

 

Perfect, that works like a a charm.

 

As per ".new-form", i am loading this div class from form.php page.  Do you have a better method for it?

Link to comment
Share on other sites

I seem to have a new issue.  It seems after I load the form and submit the message, it won't work with jquery/ajax. Here is my jquery code to send a message.

$(document).ready(function() {
				
				$(".form-submit").click(function (e) {
						e.preventDefault();
						if($(".message").val()==='')
						{
							alert("Please write a message.");
							return false;
						}
					   
						$(".form-submit").hide(); //hide submit button
					   
						var myData = 'message='+ $(".message").val(); //build a post data structure
						jQuery.ajax({
						type: "POST", // HTTP method POST
						url: "process.php", //Where to make Ajax calls
						dataType:"text", // Data type, HTML, json etc.
						data:myData, //Form variables
							success:function(response){
								$(".message").val(''); //empty text field on successful
								$(".form-submit").show(); //show submit button

							},
							error:function (xhr, ajaxOptions, thrownError){
								$(".form-submit").show(); //show submit button
								alert(thrownError);
							}
						});
				});
			});
			

It's simply not making the connection. I even tried a simple alert and still no go when I press submit.

                    <script>
			$(document).ready(function() {
				
				$(".form-submit").click(function (e) {
				      alert('hello there');
				});
			});
		    </script>
Edited by helloworld001
Link to comment
Share on other sites

At present you are setting the click function in the "ready" function after the page loads. At this point your form doesn't yet exist so the function is applied to a non-existent object. When you later create the form you now have a new object with no click function. So you need to set the click function after creating the form. In your ajax function where you write the form content, add the code to create the click function.

Edited by Barand
Link to comment
Share on other sites

  • Solution

Barand is correct about why your click event isn't triggering, but you can still assign the handler on page load using .on(). For instance

$(document).on('click','form-submit',function(){ ... });

Side note: most of the time it works if you just attach the on to the specific DOM element, but sometimes you have to attach it to document and specify the DOM element in the function call. I'm sure there's a good reason for it, but I've never been able to figure it out...

Link to comment
Share on other sites

Barand is correct about why your click event isn't triggering, but you can still assign the handler on page load using .on(). For instance

$(document).on('click','form-submit',function(){ ... });

Side note: most of the time it works if you just attach the on to the specific DOM element, but sometimes you have to attach it to document and specify the DOM element in the function call. I'm sure there's a good reason for it, but I've never been able to figure it out...

 

Thank you for the visual representation.  It works now.

Link to comment
Share on other sites

Sorry to bother you guys again but I just noticed something.

 

Everything I submit the message to the database, it will not insert the "message" text(appears empty) and the "record_id" will be same for all records inserted, no matter how many different records I submit.  Other data like "message-to" and "message-by" insert fine.

 

Here is the full page setup.

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

$user           = new User();
$mainUserid     = escape($user->data()->user_id);
?>

<!DOCTYPE HTML>
<html lang="en"> 
	<head>
		<meta charset="UTF-8">
		<title><?php echo $title; ?></title>
		<meta name="description" content="<?php echo $description; ?>">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
		<link rel="stylesheet" href="css/style.css" media="screen">
	</head>
	<body>
	
	$getRecord = $db->prepare("SELECT records.*, users.* FROM records 
	LEFT JOIN users ON records.user_id = users.user_id
	ORDER BY record_id DESC LIMIT 10");
	$getRecord->execute();
	$resultRecord = $getRecord->fetchAll(PDO::FETCH_ASSOC);
	if(count($resultRecord) < 1) {
	
		$error = '0 records found.';
		
	} else {
		
		foreach($resultRecord as $row) {
		
			$record_id		=	escape(intval($row['record_id']));
			$user_id		=	escape(intval($row['user_id']));
			$username		=	escape($row['full_name']);
			$title			=	escape($row['title']);
			$details		=	escape($row['details']);
			
			$_SESSION['record-id']	  = $record_id;
			$_SESSION['message-to']   = $user_id;
			$_SESSION['message-by']   = $mainUserid;
			
			$message                  = Input::get('message'); // HTTP method POST or GET
                        $_SESSION['message']      = $message;
			
			?>
			
			<div class="record">
			   <h1><?php echo $title; ?></h1>
			   <p><?php echo $details; ?></p>
			   <p><?php echo $user_id; ?></p>
			   <button class="button">send message</button> 
				
				<!-- this form loads through on click(.button) function -->
			   <form class="new-form">
				   <textarea name="message" class="message">Enter message</textarea>
				   <input type="button" name="submit" class="form-submit" value="Send Message">
			   </form>
			</div>
			
			<?php
		}
	}
	
	<!-- js scripts below -->
	<script src="js/jquery-1.11.0.min.js"></script>
	<script>
		$(document).ready(function(){
				$(".button").click(function(){
					$(this).parent().load("ajax/bid-form.php");
				});
			});
		</script>
		<script>
			$(document).on('click','.form-submit',function() {
				if($(".message").val()==='')
				{
					alert("Please write a message.");
					return false;
				}
			   
				$(".form-submit").hide(); //hide submit button
			   
				var myData = 'message='+ $(".message").val(); //build a post data structure
				
				jQuery.ajax({
				type: "POST", // HTTP method POST or GET
				url: "process.php", //Where to make Ajax calls
				dataType:"text", // Data type, HTML, json etc.
				data:myData, //Form variables
					success:function(response){
						$(".message").val(''); //empty text field on successful
						$(".form-submit").show(); //show submit button

					},
					error:function (xhr, ajaxOptions, thrownError){
						$(".form-submit").show(); //show submit button
						alert(thrownError);
					}
				});
				
			});
		</script>
	</body>
</html>	

And this is my process.php page.

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

$session_record_id		=	$_SESSION['record-id'];
$session_message_to 		=	$_SESSION['message-to'];
$session_message_by 		= 	$_SESSION['message-by'];
$session_message 		= 	$_SESSION['message'];

$insertMssg = $db->prepare("INSERT INTO records(record_id, message_to, message_by, message, bid_posted) VALUES(:record_id, :message_to, :message_by, :message)");
$insertMssg->bindParam(':record_id', $session_record_id);
$insertMssg->bindParam(':message_to', $session_message_to);
$insertMssg->bindParam(':message_by', $session_message_by);
$insertMssg->bindParam(':message', $session_message);
$resultInsert = $insertMssg->execute();

if($resultInsert == false) {
	
	$error = 'Your message could not be inserted.';
	
} else {

	$success = 'Your message has been added.';
	
	

}
?>
<div class="success"><?php  echo $success; ?></div>
<div class="error"><?php  echo $error; ?></div>
Edited by helloworld001
Link to comment
Share on other sites

Just some quick advice - break this out into another thread. Your original issue is solved and this one is new; as a new thread you'll probably get more traffic (and hopefully help).

 

Now, to the posted code. I'm assuming there was a copy/paste error with the 'full page setup', because you've got raw PHP in your HTML. Also, it looks like you're attempting to pass the value of the .message form field to the php script via AJAX, but you're using the value from $_SESSION, which is set in the chunk of code not contained within <?php and ?>. And I'm assuming that core/init.php calls session_start(), because I don't see that anywhere. Are you getting any errors?

Link to comment
Share on other sites

Just some quick advice - break this out into another thread. Your original issue is solved and this one is new; as a new thread you'll probably get more traffic (and hopefully help).

 

Now, to the posted code. I'm assuming there was a copy/paste error with the 'full page setup', because you've got raw PHP in your HTML. Also, it looks like you're attempting to pass the value of the .message form field to the php script via AJAX, but you're using the value from $_SESSION, which is set in the chunk of code not contained within <?php and ?>. And I'm assuming that core/init.php calls session_start(), because I don't see that anywhere. Are you getting any errors?

 

First thing.  A correction in process.php. I am actually inserting the query into "sub_records" and not "records".

 

As per your questions.

 

1. Yes I do have raw php in my html. It has never been an issue for me before and it does not give me errors.

2.  Yes I am trying to pass the value of the .message form field via AJAX.  Normally, the $_SESSION will show the value if I using a regular PHP method to submit the form.  But since I am using AJAX to submit, i am getting an empty value from the $_SESSION.

3. Yes the session_start() is in more init.php.  And no, I do not get any errors.

 

I will make this a new topic.

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.