Ravens PHP Scripts: Forums
 

 

View next topic
View previous topic
Post new topic   Reply to topic    Ravens PHP Scripts And Web Hosting Forum Index -> JavaScript
Author Message
killing-hours
RavenNuke(tm) Development Team



Joined: Oct 01, 2010
Posts: 438
Location: Houston, Tx

PostPosted: Fri Oct 29, 2010 11:45 am Reply with quote

Hello all-

Looking for a nudge here. I'm wanting to implement "real time" validation on a particular field on my form... and I've been trying to read up on just how to do it. Ajax just keeps on popping up.

Now I've seen how it works in the YA and I've even glanced in at the new_user.php and functions.php of YA... but that's a bit complicated and seems to be more confusing than anything for me at this point.

So what I'm getting at is this... do you know of any "simple" tutorials I can use to start learning how to do this? Thanks.

P.s. I posted this here because I didn't see a better place for it.

-------------------


If you are new to this topic.... I've added a simple form that submits and returns data so you can get an idea of how to implement jquery/ajax within ravennuke. It is a very simple example just to get you started.

Click to go to this post. [ Only registered users can see links on this board! Get registered or login! ]

_________________
Money is the measurement of time - Me
"You can all go to hell…I’m going to Texas" -Davy Crockett

Last edited by killing-hours on Thu Dec 09, 2010 4:03 pm; edited 1 time in total 
View user's profile Send private message
kguske
Site Admin



Joined: Jun 04, 2004
Posts: 6432

PostPosted: Fri Oct 29, 2010 6:35 pm Reply with quote

Simple is a relative term, but you might use these:
[ Only registered users can see links on this board! Get registered or login! ] [ Only registered users can see links on this board! Get registered or login! ]

_________________
I search, therefore I exist...
nukeSEO - nukeFEED - nukePIE - nukeSPAM - nukeWYSIWYG
 
View user's profile Send private message
fkelly
Former Moderator in Good Standing



Joined: Aug 30, 2005
Posts: 3312
Location: near Albany NY

PostPosted: Sat Oct 30, 2010 9:08 am Reply with quote

Killing-hours, I feel the pain with you. I've mucked around trying to learn how to do AJAX in a Ravennuke context also. My understanding, from what I've read, it that you basically should be able to:

- have a form
- in the Javascript (Jquery) associated with it, have a "link" to a PHP program that runs on the server and that program does your SQL for you, say for example getting a list of users who meet certain criteria
- then that PHP program passes the data back to the Javascript that might populate your options boxes on a select with the returned data
of course, there are pretty strict requirements such as using JSON or XML for passing data back and forth from the server side to the client side and your client side has to decode the passed in data
- then perhaps the user side does something with the data on the form (maybe using draggable and droppable boxes and then passes updates back to the server side

I honestly don't see any examples of this in the current RN code. I don't see where we are actually reading data using SQL on the server side and passing it between the two sides. But I just may be missing it.

And a lot of the documentation tends to be very difficult to figure. I have, for instance, the book Jquery in Action by Bibeault and Katz. It has a chapter on Ajax and while it is useful background, it really doesn't have the level of detail that would be needed to write code for RN. What we could really use would be a sample module using AJAX that would do some of the things I mentioned above. I guess it's up to us to do it.
 
View user's profile Send private message Visit poster's website
montego
Site Admin



Joined: Aug 29, 2004
Posts: 9457
Location: Arizona

PostPosted: Sat Oct 30, 2010 10:47 am Reply with quote

RavenNuke(tm)'s Your Account registration form could serve as a good example. Kguske wrote that and it uses AJAX for immediate identification of a duplicate user name and/or email. Check it out...

_________________
Where Do YOU Stand?
HTML Newsletter::ShortLinks::Mailer::Downloads and more... 
View user's profile Send private message Visit poster's website
Palbin
Site Admin



Joined: Mar 30, 2006
Posts: 2583
Location: Pittsburgh, Pennsylvania

PostPosted: Sat Oct 30, 2010 11:11 am Reply with quote

If you know the jquery basics I think this is fairly easy to follow. This can be used to load an entire page or just a div if that is what is returned.
[ Only registered users can see links on this board! Get registered or login! ]

_________________
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan. 
View user's profile Send private message
Palbin







PostPosted: Sat Oct 30, 2010 11:14 am Reply with quote

I would also look at the .get() and .post() functionality. I would avoid the plain .ajax() as that can get a little complicated. Just use the get and post shortcuts.
 
Palbin







PostPosted: Sat Oct 30, 2010 11:18 am Reply with quote

This is a little more than you are asking for, but you might want to read this. [ Only registered users can see links on this board! Get registered or login! ]
 
fkelly







PostPosted: Sun Oct 31, 2010 7:37 am Reply with quote

Quote:
RavenNuke(tm)'s Your Account registration form could serve as a good example. Kguske wrote that and it uses AJAX for immediate identification of a duplicate user name and/or email. Check it out...


M. I may be looking in the wrong place, but I don't see Ajax being used for this. In your_account/public there is a program called emailAvailability.php that in turn calls a function named ya_mailCheckB from your_account.includes/functions.php. ya_mailCheckB just does a simple:

Code:
   if ($db->sql_numrows($db->sql_query('SELECT user_email FROM ' . $user_prefix . '_users WHERE user_email=\'' . addslashes($user_email) . '\'')) > 0) $return = 'false';


I don't see where Ajax comes into this at all. Am I missing something? For Ajax to be in play there would have to be something in Javascript that issues a XMLHttpRequest and essentially calls a PHP program, decodes the results and processes it right inside the Javascript and form. No? Or am I looking in the wrong place?
 
Palbin







PostPosted: Sun Oct 31, 2010 11:21 am Reply with quote

The Your_Account setup is a little confusing because it uses the validation plugin, but it does use ajax.
 
fkelly







PostPosted: Sun Oct 31, 2010 11:35 am Reply with quote

I hate to be dense but can you point me to where Ajax is used? More specifically, at least the way I understand it, the Javascript is supposed to pass a request to a PHP program on the server which does some SQL and then passes data back to Javascript. Are we doing that? Where?
 
Palbin







PostPosted: Sun Oct 31, 2010 12:31 pm Reply with quote

As I said above this is a little different since it uses the validation plug-in, but here goes. If you go the the registration page on the demo site [ Only registered users can see links on this board! Get registered or login! ] we can see ajax in action.

Once you agree to the COPPA and TOS you will get to the main registration page. Type "Palbin" into the Nickname field and then click in "Real Name" field. You should now see red text below the Nickname that says "Palbin has already been registered, is blocked, or contains invalid characters". The same thing happens with the email field. The only way to do this on the fly is via ajax.

If you view source on this page you will see the following in the HEAD section.
Code:


<script type="text/javascript">
// <![CDATA[
$(document).ready(function() {
   // validate signup form on keyup and submit
   var validator = $("#newUser").validate({
      rules: {
         ya_username: {
            required: true,
            minlength: 4,
        remote: "rnxhr.php\?name=Your_Account&file=public/userAvailability"
         },ya_realname: "required",ya_user_email: {
            required: true,
            email: true,
            remote: "rnxhr.php\?name=Your_Account&file=public/emailAvailability"
            },ya_user_email2: {
            required: true,
            email: true,
            equalTo: "#ya_user_email"
            },
         user_password: {
            minlength: 8
         },
         user_password2: {
            minlength: 8,
            equalTo: "#user_password"
         }
      },
      messages: {
         ya_username: {
            required: "Please enter a user name",
            minLength: "Your username must be at least  4 characters long",
            remote: jQuery.format("{0}  has already been registered, is blocked, or contains invalid characters")
         },ya_realname: "Please enter your real name",ya_user_email: {
            required: "Please enter a valid email address",
            email: "Please enter a valid email address",
            remote: jQuery.format("{0} has already been registered or is blocked")
         },ya_user_email2: {
            required: "Please enter a valid email address",
            email: "Please enter a valid email address",
            equalTo: "Please enter the same email address as above"
         },
         user_password: {
            minLength: "Your password must be at least  8 characters long"
         },
         user_password2: {
            minLength: "Your password must be at least  8 characters long",
            equalTo: "Please enter the same password as above"
         }
      }
   });
});
// ]]>
</script>


As can be seen from the above code the validation plug-in uses ajax to call the following url to determine username availability.
Code:
remote: "rnxhr.php\?name=Your_Account&file=public/userAvailability"

I did not look in-depth to see if it uses post or get, but you can see the call in action without ajax using a get request. [ Only registered users can see links on this board! Get registered or login! ]

Off the top of my head if I was just going to use jQuery without a plug-in to do this I would probably use .POST() to post the requested username to the above url and get the true/false response back and then use plain jQuery to display or not display the error.
 
killing-hours







PostPosted: Sun Oct 31, 2010 12:32 pm Reply with quote

Right... the validation plugin is fairly simple to figure out once it's in place. I've already got that and successfully use jquery to add/remove requirements etc.

The "YA" module does use ajax validation so that on blur it checks the db for the user name availibitly. However, the way it is implemented is a bit confusing as there is so much going on in the YA module that it "seems" a bit daunting to untangle all the unnecessary stuff just to drill down to the actual way the user name field behaves.

Here's my attempt: new_user.php

Code:
echo '<p><b>* = ' . _REQUIRED . '</b></p>';

echo '<p><label for="ya_username">' . _NICKNAME . ': *</label>';
echo '<input type="text" id="ya_username" name="ya_username" size="15" maxlength="' . $ya_config['nick_max'] . '" value="' . $ya_username . '" />';
echo '<font class="tiny"><span id="userAvailability"></span></font>';
echo '<br /><label for="ya_nicklength">&nbsp;</label><input id="ya_nicklength" name="ya_nicklength" type="hidden" />';
echo '<font class="tiny">(' . _YA_NICKLENGTH . ')</font>';
echo '</p>';


Let's drill this down a bit...

The label for the field:
Code:
echo '<p><label for="ya_username">' . _NICKNAME . ': *</label>';


The input itself:
Code:
echo '<input type="text" id="ya_username" name="ya_username" size="15" maxlength="' . $ya_config['nick_max'] . '" value="' . $ya_username . '" />';


the error container for availability?
Code:
echo '<font class="tiny"><span id="userAvailability"></span></font>';


input for the length?
Code:
echo '<br /><label for="ya_nicklength">&nbsp;</label><input id="ya_nicklength" name="ya_nicklength" type="hidden" />';


error container for length?
Code:
echo '<font class="tiny">(' . _YA_NICKLENGTH . ')</font>';



Now in the userAvailibitly.php:

Code:
$ya_username = trim(strtolower($_REQUEST['ya_username']));

if ($ya_username == '') echo 'false';
else echo ya_userCheckB($ya_username);


and finally the functions.php (minus the other code in this function...just specifically the db check)
Code:
if ($db->sql_numrows($db->sql_query('SELECT username FROM ' . $user_prefix . '_users WHERE username=\'' . addslashes($username) . '\'')) > 0) $return = 'false';

   if ($db->sql_numrows($db->sql_query('SELECT username FROM ' . $user_prefix . '_users_temp WHERE username=\'' . addslashes($username) . '\'')) > 0) $return = 'false';


The JS code to make things happen:

Code:
$(document).ready(function() {

   // validate signup form on keyup and submit
   var validator = $("#newUser").validate({
      rules: {
         ya_username: {
            required: true,
            minlength: 4,
        remote: "rnxhr.php?name=Your_Account&file=public/userAvailability"
         },ya_realname: "required",ya_user_email: {
            required: true,
            email: true,
            remote: "rnxhr.php?name=Your_Account&file=public/emailAvailability"
            },ya_user_email2: {
            required: true,
            email: true,
            equalTo: "#ya_user_email"


So it seems that "rnxhr.php" is the place to find the inner workings of this I'm assuming.

rnxhr.php:

Code:
define('XHR', true);

include_once('modules.php');


So the way i'm following this is... the user types in something... on keyup the form submits the data to rnxhr.php which in turn passes that information on to userAvailibility.php and it calls on the function (ya_userCheckB) to query the db for matching data and returns it back to the functions.php which give a yes or no then returns that back to the form to display an error in one of the error containers if there is a match.

I get lost at the "remote" in the javascript to make it happen and what exactly it's doing or how it works.

-----------------------------------------

I would have to agree with fkelly in that it would be nice (for those of us still learning the in's and out's) to have a simple module that sort of explains the jist of how it works or how to make this sort of thing happen inside RN itself.

Not that it's y'alls responsibility to provide us with anything... however, it's just something else that can be documented so that when people come looking for the answer... it's already here covered "basically" and we can expand on it.

-----------------------------------------

On a side note.... I've got validation setup, working and great... yay. But the more I use it... the more I wished it looked so much better. Again I'm looking at the position absolute's version of validation and it's just absolutely gorgeous but with two problems I can see right off the bat.

1. The is no way to use submitHandlers in the same fashion that the regular validation plugin works. (unless I just don't understand the way it's coded)

2. I haven't tried playing with this option yet... and it may be accomplished by adding attributes via jquery... but a way to dynamically add rules based on another inputs ".click" or ".change". (similar to how the regular validator does ("add", "required") )

So I've been floating the idea of getting those two problems solved so that RN could benefit from this beautiful validator.

does it seem worth it or is this a waste of time in your opinion?

screenshot of the validation error (no error labels used... just the input):
Image

Thanks again for all the input guys... It really helps shed new light on things.



--------------

EDIT**** Sorry Palbin... You posted your response as I was coming up with mine.
 
Palbin







PostPosted: Sun Oct 31, 2010 1:10 pm Reply with quote

Quote:

EDIT**** Sorry Palbin... You posted your response as I was coming up with mine.


Happens to me all the time Cheers
 
montego







PostPosted: Sat Nov 06, 2010 3:18 pm Reply with quote

fkelly wrote:
I hate to be dense but can you point me to where Ajax is used? More specifically, at least the way I understand it, the Javascript is supposed to pass a request to a PHP program on the server which does some SQL and then passes data back to Javascript. Are we doing that? Where?


kguske has the username and email address using AJAX to validate these against the users table. All you have to do is cursor out of the field and it goes and checks...
 
hicuxunicorniobestbuildpc
The Mouse Is Extension Of Arm



Joined: Aug 13, 2009
Posts: 1122

PostPosted: Sat Nov 06, 2010 6:32 pm Reply with quote

I hope ajax comes together with jquery for the next version of ravennuke. Ajax looks really cool.

take a look

Code:
function callAHAH(url, dlid, pageElement, callMessage, errorMessage) {

     document.getElementById(pageElement).innerHTML = callMessage;
     try {
     req = new XMLHttpRequest(); /* e.g. Firefox */
     } catch(e) {
       try {
       req = new ActiveXObject("Msxml2.XMLHTTP");  /* some versions IE */
       } catch (e) {
         try {
         req = new ActiveXObject("Microsoft.XMLHTTP");  /* some versions IE */
         } catch (E) {
          req = false;
         }
       }
     }
     req.onreadystatechange = function() {responseAHAH(pageElement, errorMessage);};
     req.open("GET",'usercheck.php?fid='+url+'&dlid='+dlid,true);
     req.send(null);
  }

function responseAHAH(pageElement, errorMessage) {
   var output = '';
   if(req.readyState == 4) {
      if(req.status == 200) {
         output = req.responseText;
         document.getElementById(pageElement).innerHTML = output;
         } else {
         document.getElementById(pageElement).innerHTML = errorMessage+"\n"+output;
         }
      }
  }
 
View user's profile Send private message
Raven
Site Admin/Owner



Joined: Aug 27, 2002
Posts: 17088

PostPosted: Sat Nov 06, 2010 8:35 pm Reply with quote

unicornio,

Not sure what you mean by "comes together". We started using it to our advantage in v2.40 and will continue Smile.
 
View user's profile Send private message
fkelly







PostPosted: Mon Nov 08, 2010 10:41 am Reply with quote

Thanks to Killing-hours and Palbin's posts I can see where we use Ajax in RN now. However, in rnxhr.php we do this:

Code:
define('XHR', true);

include_once('modules.php');


Am I missing something or did we just take a shortcut? The text books and documentation I am looking at seem to indicate that we should be determining whether the browser supports the XHR object and there are different calls depending on whether you are using IE or not.
 
montego







PostPosted: Tue Nov 09, 2010 6:54 am Reply with quote

fkelly, at the browser end, jQuery's AJAX support already takes care of that (the XHR support), so not sure what "shortcut" you are referring to?
 
fkelly







PostPosted: Tue Nov 09, 2010 10:17 am Reply with quote

I guess that's what I get for reading my ... manual. The code I am seeing in my Jquery Ajax chapter goes like this:

Code:


var xhr;
if (window.XMLHttpRequest) {
   xhr = new XMLHttpRequest;
}
else if (window.ActiveXObject) {
  xhr = new ActiveXObject("Maxml2.XMLHTTP");
else .. an error is displayed


So, you are saying Jquery takes care of all this. And there is no danger if we just define XHR as true.
 
hicuxunicorniobestbuildpc







PostPosted: Tue Nov 09, 2010 2:00 pm Reply with quote

Shocked
Quote:
We started using it to our advantage in v2.40


I didn't notice RavenNuke is using ajax. Can you specify what kind of files are running ajax?

Very Happy
 
fkelly







PostPosted: Tue Nov 09, 2010 3:24 pm Reply with quote

Unicornio ... both killing-hours and Palbin have posted pretty detailed analyses of how RN uses AJAX right in this thread.
 
killing-hours







PostPosted: Tue Nov 09, 2010 4:13 pm Reply with quote

<facepalm> Bang Head
 
Palbin







PostPosted: Tue Nov 09, 2010 5:50 pm Reply with quote

fkelly wrote:
I guess that's what I get for reading my ... manual. The code I am seeing in my Jquery Ajax chapter goes like this:

Code:


var xhr;
if (window.XMLHttpRequest) {
   xhr = new XMLHttpRequest;
}
else if (window.ActiveXObject) {
  xhr = new ActiveXObject("Maxml2.XMLHTTP");
else .. an error is displayed


So, you are saying Jquery takes care of all this. And there is no danger if we just define XHR as true.


The definition of XHR you are seeing in PHP has absolutely nothing to with jQuery. It is used to tell the "Who is Where" script to execute or not.

fkelly I do not know the context of how that code is presented, but that is not jQuery. It looks like plain JavaScript. Are they possibly trying to explain what jQuery does when you use a certain bit of code?

Also what are you meaning by "danger"? Is there a particular security concern you have? Are you looking to not execute the script if it is not an ajax request?
 
killing-hours







PostPosted: Tue Nov 09, 2010 7:03 pm Reply with quote

Palbin-

I believe what fkelly is referring to is how to determine if the browser "supports" XHR.

(i.e. IE6 does not)

Quote:
Internet Explorer versions 5 and 6 did not define the XMLHttpRequest object identifier in their scripting languages as the XMLHttpRequest identifier itself was not standard at the time of their releases.[6] Backward compatibility can be achieved through object detection if the XMLHttpRequest identifier does not exist.

An example of how to instantiate an XMLHttpRequest object with support for Internet Explorer versions 5 and 6 using JScript method ActiveXObject is below.

Code:
/*

   Provide the XMLHttpRequest constructor for IE 5.x-6.x:
   Other browsers (including IE 7.x-8.x) do not redefine
   XMLHttpRequest if it already exists.
 
   This example is based on findings at:
   http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
*/
if (typeof XMLHttpRequest == "undefined")
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (e) {}
    //Microsoft.XMLHTTP points to Msxml2.XMLHTTP.3.0 and is redundant
    throw new Error("This browser does not support XMLHttpRequest.");
  };


[ Only registered users can see links on this board! Get registered or login! ]

The method used in the rnxhr.php is to define the support as "True" regardless of the browser. (which could cause problems in older browsers if I'm understanding this correctly)


Note*** Keep in mind I have no idea what I'm talking about with this stuff so I could be totally off base. Just my .02 on the matter.

Please correct me if I'm wrong somewhere so that I get a better idea of how all this works.
 
fkelly







PostPosted: Wed Nov 10, 2010 9:48 am Reply with quote

@palbin, killing-hours explained what I was getting at. The code I copied in was from the JQUERY in action book and it was indeed showing Javascript and how to determine if the browser supports XHR. And, as Killing-Hours says, it looks to me that the method used in rnxhr.php does define support of Ajax as true regardless of whether the browser supports it. Could this approach not cause problems in some instances?

The "call" to rnxhr.php that I am quoting is in jquery.php which is in turn in the /includes directory. On sample looks like this:

Code:
$(document).ready(function() {

   // validate signup form on keyup and submit
   var validator = $("#newUser").validate({
      rules: {
         ya_username: {
            required: true,
            minlength: '.$ya_config['nick_min'].',
        remote: "rnxhr.php?name=Your_Account&file=public/userAvailability"


So I am guessing that rnxhr is getting executed in the context of YA where the user is typing in a username and we are using Ajax to see if that username is available. We only provide the squished version of jquery.validate.js in our distribution so it takes a couple of steps (looking on the web) to begin to figure out what "remote:" does. It appears to be a function within the validate.js file and the documentation says this:

Quote:
Requests a resource to check the element for validity.
The serverside resource is called via $.ajax (XMLHttpRequest) and gets a key/value pair, corresponding to the name of the validated element and its value as a GET parameter. The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message. For more examples, take a look the marketo demo and the milk demo.


Decrypted, I think all we are doing with AJAX in YA at this time is a simple lookup that returns true or false. To go further we will need to do something where we return a set of values (say all usernames or nsngroups) and then populate a drop down with them, let people update and then apply the updates by AJAX. I can see the applicability for something like improving the nsngroups admin screen but it takes time that I don't have.
 
Display posts from previous:       
Post new topic   Reply to topic    Ravens PHP Scripts And Web Hosting Forum Index -> JavaScript

View next topic
View previous topic
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You can attach files in this forum
You can download files in this forum


Powered by phpBB © 2001-2007 phpBB Group
All times are GMT - 6 Hours
 
Forums ©