Forums

Adapting AJAX script to populate field from db data

dmontpe 30 Jun, 2011
I need to automatically populate one field with data from my database. (When a user ID field is filled out, the user name is retrieved from the db and the field is populated) I found this AJAX script I would like to adapt but I have one question:

The form html includes this tag:

<form name="clientForm" action="ajax-client_lookup.html" method="post">	


Now, since CF automatically generates the form tag, how do I add that action property to the form tag?

Suggestions for other scripts or other ways to accomplish this are welcome, too.

David
GreyHead 01 Jul, 2011
Hi dmontpe,

The whole idea of using Ajax is that the form doesn't have to be submitted to get the data - so the idea of using the form action for the script baffles me.

Technically you an set this as the form OnSubmit URL but then ChronoForms will never see the form data, and the user will be sent to the ajax page. I don't think that is what you want.

There's an article from The ChronoForms Book here on using Ajax to check an email address that you can probably adapt.

Bob
dmontpe 01 Jul, 2011
Thanks for the suggestion, Bob. I'm giving it a try. Now, I'm guessing this article was written for an older version of CF since I can't find the Extra Code box in V4. How do I go about that? Where do I place that code?

Thanks.

David
GreyHead 01 Jul, 2011
Hi David,

I'll try to write this up properly over the weekend. There is a brief description in the forums here somewhere.

You need to create a new Event called say, 'ajax', with the button under the OnSubmit event box and add the Ajax response code there. The url then has event=ajax in the url insatead of task=extra.

Bob

PS Unfortunately a bug in CFv4 adds the strap-line to the Ajax response. There a fix for this in the bugs list post.
dmontpe 01 Jul, 2011
It would be just awesome if you do it. (I repeat, IF you do it, I won't hold you accountable if you don't) I have enough trouble trying to wrap my head around the little PHP I need right now! I will get busy with other stuff today and cross my fingers that you are able to work on it for next week.

Thank you so much, Bob!

David

P.S. I know this could backfire on me, but you shouldn't work so much on weekends! :wink: (I noticed you replied to another post on a Sunday, too)
dmontpe 07 Jul, 2011

P.S. I know this could backfire on me, but you shouldn't work so much on weekends! :wink: (I noticed you replied to another post on a Sunday, too)



Hi, Bob! I guess you took my advice and took a break last weekend.🙂 I was wondering if you still think you'll be able to write up something for this matter. Do you?
GreyHead 07 Jul, 2011
Hi David,

I did indeed take a break .. . and also did some client work which happened to include an Ajax link using MooTools 1.2.5 so I have go the code to work. Just need to write it up.

Bob
jarodwildcat 10 Jul, 2011
I've been able to get the example to work with CFv4. I've created a custom event ajaxEvent and made some changes in the mootool script.
Here is my custom code for the event:
<?php
// clean up the JSON message

$email = strtolower(trim($_GET['email']));
// check that the email field isn't empty
$response = false;
if ( $email ) {
  // Check the database
  $db =& JFactory::getDBO();
  $query = "SELECT COUNT(*) FROM `#__users` WHERE LOWER(`email`) = ".$db->quote($email).";";
  $db->setQuery($query);
  $response = (bool) $db->loadResult();
}
$response = array('email_ok' => $response );
//send the reply

echo json_encode($response);
// stop the from running
$MyForm->stopRunning = true;
die;
?>


and here is my JS code:
window.addEvent('domready',	function() {
  // set the url to send the request to
  var url = 'index.php?option=com_chronoforms&chronoform=form4&event=ajaxEvent&format=raw';
  var email = $('email');
  email.addEvent('blur', function() {
  // clear any background color from the input
  email.setStyle('background-color', 'white');
  // check that the email address is valid
  regex = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i;
  var value = email.value.trim();
  if (value.length > 6 && regex.test(value)) {
	// if all is well send the JSON request
	var jSonRequest = new Request.JSON({
		url : url,
		method : 'get',
		data : {email : email.value},
		onComplete : function(r) {
		  // check the result and set the background
		  // color
		  //console.log(r);
		  if (r.email_ok) {
			email.setStyle('background-color','green');
		  } 
		  else {
			email.setStyle('background-color','red');
		  }
		}
	}).send();
  } else {
	  // if this isn't a valid email set background color
	  // red
	  email.setStyle('background-color', 'red');
  	}
  });
});


Hope this helps.

Jarod.
dmontpe 11 Jul, 2011
Thank you, jarod. And excuse my stupidity, but where do you put each piece of code? I'm pretty sure that if I get that, then I will be able to work on adapting the code to do what I need. That's what threw me off about the original code: it was supposed to go in "Extra code 1" which doesn't exist in CFv4. I will appreciate it if you can point me in the right direction with that.

David

P.S. I'm sorry if I sound slow but if my php knowledge is already quite limited, my JS and AJAX knowledge is down to zero.
GreyHead 17 Jul, 2011
Hi,

I have now written this up in a tutorial that you can get for a few $ here. This includes both the Email lookup and the Double Drop-down
Ajax examples.

Bob
jarodwildcat 22 Jul, 2011
David,

I put the JS code in the 'onLoad' Event (via loadJS) and the php in the new event section I created.
Specifically, you need to edit your form in advanced mode and go to the event tab. Drag the 'Load JS' from the Action tab (left column) to the 'Load JS' section (right column) and put your JS code there.
Then create a new event by clicking on the green plus ('add event') at the bottom of the page (still under event tab, right column). Choose a name for your new event. I used 'ajaxEvent'. Then add the php code as the event code.

PS: Not sure if it's obvious, but the middle icon next to the red cross is the one you use to add/edit code.

Jarod.
dmontpe 22 Jul, 2011
Thank you, jarod. You pointed something tha should be obvious but I missed: that I should use the Load JS. I've got Bob's new version of the tutorial so now that I got the original script working, I can get to work to modify it so it does what I want.

P.S. Bob, no need to check my form now. Thanks again.
dmontpe 22 Jul, 2011
OK. I think I'm almost there though I'm stuck again. What this is supposed to do is to use the 'patroc_id' field to search the database and populate the 'patroc_nombre' field with the retrieved data. I've taken Bob's tutorial and have changed all I know to adapt it but js is really like chinese to me (I can stare at it for an hour and the only things I get are 'var', 'if' and 'else'!).

I think (though I might be totally wrong) that I only need to add a line or two to take the response from the PHP script and populate the 'patroc_nombre' field. If anyone can tell me how to do that, I'll appreciate it so much. (Pointers on any errors you see are welcome, too!)


This is the js I have so far:

window.addEvent('domready', function() {
// set the url to send the request to
var url =
'index.php?option=com_chronoforms&chronoform=form_inscripcion&event=ajax&format=raw';
var patroc_id = $('patroc_id');
patroc_id.addEvent('blur', function() {
// check that the email address is valid
regex = [0-9]+;
var value = patroc_id.value.trim();
if ( value.length >= 6 && regex.test(value) ) {
// if all is well send the JSON request
var request = new Request({
method: 'post',
url: url,
data: { 'patroc_id' : patroc_id },
onComplete: function(r) {
// Populate patroc_nombre with the response from the PHP script ???????????????????????????

}
}).send();
}
});
});


This is my PHP:

<?php
// Get the query info
$patroc_id = JRequest::getString('patroc_id', '', 'post');
$patroc_id = trim($patroc_id);
$patroc_id = ltrim($patroc_id,"0");
if ( $patroc_id ) {
// Retrieve sponsor's name from database
$db =& JFactory::getDBO();
$query = "
    SELECT apellidos, nombres
	FROM `#__data_usuarios`
	WHERE `usu_id` = ".$patroc_id.";";
$db->setQuery($query);
$result = $db->loadAssoc();
if ( $result ) {
   $response = $result['nombres'].$result['apellidos'];
   }
else {
   $response = "-- El código no existe --"; 
   }   
//Send the reply
echo $response;
?>


Thanks to any generous soul.

David
GreyHead 23 Jul, 2011
Hi David,

Have you got this working? If not, please will you post the part of the HTML where you want the result to display.

Bob
dmontpe 25 Jul, 2011
Hi, Bob:

Not yet. This is the input that should be populated:

<input id="patroc_nombre" maxlength="70" size="30" class="" title="Verifica que el nombre de tu patrocinador sea correcto" type="text" value="" name="patroc_nombre" />


I guess this is enough, if you need to see anything else, just let me know.

David
GreyHead 25 Jul, 2011
Hi David,

I think that the answer is
onComplete: function(r) {
  // Populate patroc_nombre with the response from the PHP script ???????????????????????????
  $('patroc_nombre').value = result;
}

Bob
dmontpe 26 Jul, 2011
Hi, Bob et all. Here again! 😢 I added the line and tested the code and nothing happens.

Now, I have discarded a couple things as the source of error: (1) The original email checking code was working OK so the CF actions setup and code locations are fine. (2) I have tested the php part manually defining $patroc_id and it worked fine, so the problem is either in the first line of php which receives the contents for $patroc_id or the js code.

Could you take a look and see if you can spot what I missed?

Just to clarify, the two inputs involved are tagged id="patroc_id" and id="patroc_nombre". What it should do is that when you input the patroc_id, patroc_nombre should be automatically populated with the corresponding name from the database. Here's the code again:

<script type="text/javascript">
window.addEvent('domready', function() {
// set the url to send the request to
var url =
'index.php?option=com_chronoforms&chronoform=form_inscripcion&event=ajax&format=raw';
var patroc_id = $('patroc_id');
patroc_id.addEvent('blur', function() {
// check that the email address is valid
regex = [0-9]+;
var value = patroc_id.value.trim();
if ( value.length >= 6 && regex.test(value) ) {
// if all is well send the JSON request
var request = new Request({
method: 'post',
url: url,
data: { 'patroc_id' : patroc_id },
onComplete: function(r) {
// Populate patroc_nombre with $response
$('patroc_nombre').value = result;
}
}).send();
}
});
});
</script>


<?php
// Get the query info
$patroc_id = JRequest::getString('patroc_id', '', 'post');
$patroc_id = trim($patroc_id);
$patroc_id = ltrim($patroc_id,"0");
if ( $patroc_id ) {
// Retrieve sponsor's name from database
$db =& JFactory::getDBO();
$query = "
    SELECT apellidos, nombres
	FROM `#__data_usuarios`
	WHERE `usu_id` = ".$patroc_id.";";
$db->setQuery($query);
$result = $db->loadAssoc();
if ( $result ) {
   $response = $result['nombres'].' '.$result['apellidos'];
   }
else {
   $response = '-- El código no existe --'; 
   }
}
//Send the reply
echo $response;
?>


Thanks a lot.

David
dmontpe 04 Aug, 2011
Well, I haven't figured this out yet, so I'll just push this up one more time to see if anyone can give me a hand. If you know any javascript, take a look at the post just above this one, please. I will really appreciate it if you can tell me what's wrong in that code.

David
GreyHead 05 Aug, 2011
Hi David,

By all means email or PM me the site URL and a SuperAdmin login and I'll take a quick look.

Bob
This topic is locked and no more replies can be posted.