Jump to content

Using Ajax to transfer data


Go to solution Solved by Ch0cu3r,

Recommended Posts

I am trying to write a basic Private Messaging script.

 

I have my main page which lists all messages that have been received. I then want to click on an href link to run an ajax query to bring information in from another .php file which shows the content of the selected message.

 

But I can't fathom out how to do this with an href. First off, is it possible? If so, can anyone tell me what I am doing wrong?

 

The relevant script is:

 

privatemessage.php:

<?php
$query2 = DB::getInstance()->query("SELECT 
                c.id as cid, c.title, c.time, 
		m.id as membersid, m.username, 
		m.member_first_name, m.member_last_name 
		FROM conversation as c, members as m
		WHERE ((c.member1='{$memberid}' 
		and c.read1='Yes' and c.removed1='No' 
		and m.id=c.member2) 
		OR (c.member2='{$memberid}' and c.read2='Yes' 
		and c.removed2='No' and m.id=c.member1)) 
		GROUP BY m.id ORDER BY m.id DESC");
?>

<table>
<tr>
	<td align="left">
		<?php echo htmlentities($result2->member_first_name); ?>
		<?php echo htmlentities($result2->member_last_name); ?>
		<?php echo "("; echo htmlentities($result2->username); echo ")"; ?>
	</td>
	<td align="right">
		<?php echo timeAgo(strtotime($result2->time)); ?>
	</td>
</tr>
<tr>
	<td colspan="2" align="left">
		<form action="" method="post">	
		<?php echo "Subject: "; ?>
		<?php echo "<input type='hidden' name='id' id='id' value='{$result2->cid}'>"; ?>
		<a href="#$result2->cid" onClick="showMessages(this.value)"><?php echo htmlentities($result2->title); ?>
		</form>
		<script src="//code.jquery.com/jquery-1.10.2.js"></script>
		<script src="js/readmessage.js"></script>
	</td>
</tr>

My readmessage.js code is:

function showMessages(str)
{
if (str=="")
  {
  document.getElementById("txtMessage").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtMessage").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","readmessage.php?q="+str,true);
xmlhttp.send();
}

And my readmessage.php code is:

<?php
require 'core/memberinit.php';
$member = new Member();
include 'timeago.php';

$memberid = $member->data() ->id;

if(isset($_GET['q'])) {
	$q = html_entity_decode($_GET['q']);
	
	$req1 = DB::getInstance()->query("SELECT title, member1, member2 FROM conversation WHERE id='{$q}' AND id2='1'");
	
	foreach ($req1->results() as $dn1)
	
	if($req1->count()==1)
	{
		if(($dn1->member1=='{$memberid}') or ($dn->member2=='{$memberid}'))
		{
			if($dn1->member1=='{$memberid}')
			{
				DB::getInstance()->query("UPDATE conversation SET read1='Yes' where id='{$q}' and id2='1'");
				$user_partic = 2;
			} else {
				DB::getInstance()->query("UPDATE conversation SET read2='Yes' where id='{$q}' and id2='1'");
				$user_partic = "1";
			}
			$req2 = DB::getInstance()->query("SELECT conversation.time, conversation.message, 
						members.id as userid, members.username, members.member_first_name, members.member_last_name 
						FROM conversation, members 
						WHERE conversation.id='{$id}' AND members.id=conversation.member1 
						ORDER BY conversation.id2");
			if(isset($_POST['message']) and $_POST['message']!='')
			{
				$message = $_POST['message'];
				if(get_magic_quotes_gpc())
				{
					$message = stripslashes($message);
				}
				$message = $string(nl2br(htmlentities($message, ENT_QUOTES, 'UTF-8')));
				if(	DB::getInstance()->query("INSERT into conversation 
					(id, id2, title, member1, member2, message, time, read1, read2)
					VALUES('{$q}', '{(intval($req2->id2)+1)}', '', '{$memberid}', '', '{$message}', '.time().', '', '')") 
					and 
				DB::getInstance()->query("UPDATE conversation SET read'{$user_partic}'='Yes' WHERE id='{$q}' AND id2='1'"));
			}
			echo "<h4>";
			echo $dn1->title; 
			echo "</h4><br><br>";
			echo "<table><col width='150px'><col width='50px'><col width='150px'>";
			echo "<tr><th>Member</th><th>&nbsp</th><th>Message</th></tr>";
			
			foreach ($req2->results() as $dn2)
			{
			echo "<tr><td>";
			echo $dn2->members.member_first_name;
			echo $dn2->members.member_last_name;
			echo " (";
			echo $dn2->members.username;
			echo ")	</td><td></td><td>";
			echo timeAgo(strtotime($dn2->time));
			echo "<br>";
			echo $dn2->message;
			echo "</td></tr>";
			}
			echo "</table>";
		}
	}
}
?>

However, just to try and find where the error lies, I have tried the following code for my readmessage.php file:

<?php
require 'core/memberinit.php';
$member = new Member();
include 'timeago.php';

$memberid = $member->data() ->id;

if(isset($_GET['q'])) {
	$q = intval($_GET['q']);

echo $q;
}
?>

Which always returns a "0" reply - which says to me that my files are talking, but that the id isn't being carried across.

 

Anybody got any suggestions?

 

Many thanks for any help offered.

Link to comment
https://forums.phpfreaks.com/topic/292598-using-ajax-to-transfer-data/
Share on other sites

What is  this.value  supposed to refer to here?

<a href="#$result2->cid" onClick="showMessages(this.value)"><?php echo htmlentities($result2->title); ?>

this will always refer to the anchor tag when it is clicked.

 

I guess you mean to pass the value of the id input field to your showMessages function? In which case use getElementById to target that input field in your showMessages function.

<a href="#$result2->cid" onClick="showMessages()"><?php echo htmlentities($result2->title); ?>


...
<script>
function showMessages()
{
   // get the value of the value of id input
   var theId = document.getElementById('id').value;

   ... code for xmlhttprequest omitted here ...

   // for debug purposes only. Display the id being sent to readmessage.php
   alert("The ID pass to readmessage.php is: " + theId);

   xmlhttp.open("GET","readmessage.php?q="+theId,true);
   xmlhttp.send();
}
</script>
Edited by Ch0cu3r

Thanks for that. It's definitely making a difference - namely I'm not getting a '0' or undefined value.

 

However, the debug value is showing the id of the last message in the loop, rather than the ID for each individual message.

 

I've amended my coding as follows:

 

privatemessage.php

<?php
$query2 = DB::getInstance()->query("SELECT 
                c.id as cid, c.title, c.time, 
		m.id as membersid, m.username, 
		m.member_first_name, m.member_last_name 
		FROM conversation as c, members as m
		WHERE ((c.member1='{$memberid}' 
		and c.read1='Yes' and c.removed1='No' 
		and m.id=c.member2) 
		OR (c.member2='{$memberid}' and c.read2='Yes' 
		and c.removed2='No' and m.id=c.member1)) 
		GROUP BY m.id ORDER BY m.id DESC");
?>

<table>
<tr>
	<td align="left">
		<?php echo htmlentities($result2->member_first_name); ?>
		<?php echo htmlentities($result2->member_last_name); ?>
		<?php echo "("; echo htmlentities($result2->username); echo ")"; ?>
	</td>
	<td align="right">
		<?php echo timeAgo(strtotime($result2->time)); ?>
	</td>
</tr>
<tr>
	<td colspan="2" align="left">
		<form action="" method="post">	
		<?php echo "Subject: "; ?>
		<?php echo "<input type='hidden' name='id' id='id' value='{$result2->cid}'>"; ?>
		<a href="#$result2->cid" onClick="showMessages()"><?php echo htmlentities($result2->title); ?>
		</form>
		<script src="//code.jquery.com/jquery-1.10.2.js"></script>
		<script src="js/readmessage.js"></script>
	</td>
</tr>

readmessage.js

function showMessages()
{
	// get the value of the value of id input
	var theId = document.getElementById('id').value;
	if (window.XMLHttpRequest)
	{
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	} else {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange=function()
	{
		if (xmlhttp.readyState==4 && xmlhttp.status==200)
		{
			document.getElementById("txtMessage").innerHTML=xmlhttp.responseText;
		}
	}

	// for debug purposes only. Display the id being sent to readmessage.php
	alert("The ID pass to readmessage.php is: " + theId);

	xmlhttp.open("GET","readmessage.php?q="+theId,true);
	xmlhttp.send();
}

CroNiX - I understand why you're frustrated with me. But you should understand what my learning curve has been. I've always loved the functionality of excel and writing great programmes for it. So, last Christmas my wife bought me a book called 'PHP & MySQL in easy steps' because she thought I would find the problem solving of writing a website fun. And I have. As a hobby I have been trying to write a website by coding from the ground up - no dreamweaver or such like, just self teaching of coding and css. This has progressed to using PHP and MySQL and I am only now venturing into using JQuery. So my intention is to learn this and implement it's powerful functions, but it is all a very steep learning curve and I am mostly relying on Google to find resources. But I will get there and, hopefully, one day it would be nice to be one of the people on here helping other people who are in the position that I am in today. With another Christmas fast approaching, can you recommend a good book to help me learn the intricacies of JQuery? :)

 

Ch0cu3r - Awesome. Thank you. That works a treat.

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.