Forum Moderators: open

Message Too Old, No Replies

Ajax - Multiple Value Issues

One Ajax Function with Multiple Values Call

         

Sherif

2:54 pm on Mar 11, 2011 (gmt 0)

10+ Year Member



Hey Guys...

I've been working on an AJAX script that will perform a call on a PHP page sending the variables it receives to that page, and return the results to the page.

The code that i am working on is very good when i use only one text field. For some reason, I cannot find anything that explains if hi have more than one field.

Example:

I want to search for names of people in my site, so there is FirstName, and LastName.

How do i tell the javascript to populate the appropriate fields?

The Code that i am currently using is the following.. it is very simple (preliminary)
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("container").innerHTML="<p style='text-align:center;'>Please Type In A Name To Retrieve Results</p>";
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==1 || xmlhttp.readyState==3)
{
src = "ajax-loader.gif";
document.getElementById("container").innerHTML="<img style='margin-left:450px; margin-top:15px;' src='" + src + "'>";

}

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("container").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","NameResult.php?FirstName="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>


I used the encode=URIComponent as there are some non-english names.

There is currently one text field with the following properties:
<form id="form1" name="form1" method="post" action="">
<label for="name">First Name:</label>
<input dir="rtl" type="text" name="FirstName" id="FirstName" onkeyup="showUser(this.value)" />
</form>


How can i add another text field for the LastName, and call the same function, sending the lastname variable, to the PHP page?

I also do not wanted it to depend on which input starts first...


Thanks a lot for the support.

Sincerely,
Sherif

Fotiman

3:30 pm on Mar 11, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




xmlhttp.open("GET","NameResult.php?FirstName="+encodeURIComponent(str),true);

You have hard coded the "FirstName" as part of the URL. So you'll need to make that variable depending on which input is being used. So first change your function to take in another parameter:

function showUser(str, id)


Next, update the URL to use that value:

if (id !== "FirstName") {
id = "LastName";
}
xmlhttp.open("GET","NameResult.php?"+id+"="+encodeURIComponent(str),true);

Note, I've added a bit of a safety net here to allow only FirstName and LastName as the id values.

Lastly, update your inputs:

<input dir="rtl" type="text" name="FirstName" id="FirstName" onkeyup="showUser(this.value, this.id)" />
<input dir="rtl" type="text" name="LastName" id="LastName" onkeyup="showUser(this.value, this.id)" />

Sherif

4:57 pm on Mar 11, 2011 (gmt 0)

10+ Year Member



Hey Fotiman,

I can see what you are trying to do.. but according to this, you decide on whether the input is either from the FirstName, or LastName only, but we cannot use both...

In my case, I would like to use both, and not only one of them.

Example... Lets say a user searches for Joe as the first name, the output could be like 20 Results, I want to even add more filter to the result when the user types the last name ex Mark, the output would end up with 3 Results for example instead of the 20. (having the query search the database using both the firstname and lastname instead of having it search for either on of them.)


The opposite should also happen, meaning that they could start by typing in the last name, and then the first and the same thing should also happen.


How could we make that script flexible enough to send these various variables?

Thanks a lot for the support.

Sincerely,
Sherif

Fotiman

5:42 pm on Mar 11, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




In my case, I would like to use both, and not only one of them.

Ok, that wasn't clear from your original post. In that case, I would modify your function to fetch the values from the form (instead of trying to pass in a value).


function showUser()
{
var FirstName = document.getElementById('FirstName'),
LastName = document.getElementById('LastName');


Then change your inputs:

<input dir="rtl" type="text" name="FirstName" id="FirstName" onkeyup="showUser()" />
<input dir="rtl" type="text" name="LastName" id="LastName" onkeyup="showUser()" />


Then in your function, check to see which fields have values and use that to create the query string. Here's what I came up with:


function showUser() {
var FirstName = document.getElementById('FirstName'),
LastName = document.getElementById('LastName');
var querystr = "";
if (FirstName.value != "") {
querystr += "FirstName=" + encodeURIComponent(FirstName.value);
}
if (LastName.value != "") {
querystr += (querystr.length == 0? "" : "&") + "LastName=" + encodeURIComponent(LastName.value);
}
if (querystr == "") {
document.getElementById("container").innerHTML = "<p style='text-align:center;'>Please Type In A Name To Retrieve Results</p>";
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 == 1 || xmlhttp.readyState == 3) {
src = "ajax-loader.gif";
document.getElementById("container").innerHTML = "<img style='margin-left:450px; margin-top:15px;' src='" + src + "'>";

}

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("container").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "NameResult.php?" + querystr, true);
xmlhttp.send();
}


One thing to note... this only checks to see if the value is "". You should instead trim off any leading or trailing whitespace, otherwise if the value is:
" Fotiman"
Then it may not match any records. In other words, if the user enters nothing but spaces, it will search for those values.

I'll leave it as an exercise for you to do the trimming. :)

Sherif

10:11 pm on Mar 11, 2011 (gmt 0)

10+ Year Member



Woow! Fotiman!

You are always my savior!

I have never thought of doing it this SIMPLE way... for some reason, I always try to complicate stuff for myself, and i began trying to find a tutorial on how to call a function multiple times, and how to identify which type of variable i am trying to pass on each function call.

As you always do... You always to like to keep something missing for me to research.... Thanks to jQuery! They provide the Simple Tool for beginners like me:

jQuery.trim


THIS Saved my DAY! :P

Any way... thanks for the tip... you Saved ME, and I am going to deal with the same concept to identify the sort type and the other variables.!

Again... Thank YOU!


Sincerely,
Sherif

Sherif

10:27 pm on Mar 11, 2011 (gmt 0)

10+ Year Member



Ohhh By the way,

the modifications that i used was as follows:
function showUser() {
var FirstName = jQuery.trim(document.getElementById('FirstName').value),
LastName = jQuery.trim(document.getElementById('LastName').value);


I was wondering, why did you get it as an element, and each time, when you wanted to get the value, you used FirstName.value every time you wanted to call the value of what was stored.

As you can expect, that since i stored the values directly in the variable, i removed all of the instances of the .value in the remaining component of the script.

I just want to make sure that i am not doing something critically incorrect.

Thanks for the explanation in advance.

Sincerely,
Sherif

Fotiman

8:17 pm on Mar 12, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




I was wondering, why did you get it as an element, and each time, when you wanted to get the value, you used FirstName.value every time you wanted to call the value of what was stored.

No reason other than I was in a rush when I typed that up. :)

Sherif

2:18 pm on Mar 29, 2011 (gmt 0)

10+ Year Member



Hey Guys,

Noticed that my script has a wierd error when i run it on IE8.

As you have probably read earlier, I have a form on my page, and some elements.

When the page first loads, I get the following error.

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; WOW64; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2; InfoPath.1)
Timestamp: Tue, 29 Mar 2011 13:56:46 UTC


Message: Object doesn't support this property or method
Line: 21
Char: 3
Code: 0
URI: [domain.com...]

Please note that line 21 is the bold line in the code above.

P.s. I get no errors in Safari or Firefox.

Thanks a lot for your support.

Sincerely,
Sherif

If i hit the refresh button, and try an input everything works normaly.

If a load a page from the begining, i get the error mentioned above.
Any suggestions for that?

The script that i am using:

<script type="text/javascript">
function showUser() {
var FirstName = jQuery.trim(document.getElementById('FirstName').value),
LastName = jQuery.trim(document.getElementById('LastName').value),
Language = document.getElementById('Language').value, PhoneNum = jQuery.trim(document.getElementById('Number').value);

var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

var querystr = "";
if (FirstName != "") {
querystr += (querystr.length == 0? "" : "&") + "FirstName=" + encodeURIComponent(FirstName);
}
if (LastName != "") {
querystr += (querystr.length == 0? "" : "&") + "LastName=" + encodeURIComponent(LastName);
}
if (PhoneNum != "") {
querystr += (querystr.length == 0? "" : "&") + "Num=" + PhoneNum;
}
if (querystr == "") {
document.getElementById("container").innerHTML = "<p style='text-align:center;'>Please Type In A Name To Retrieve Results</p>";
return;
}
if (Language != "") {
querystr += (querystr.length == 0? "" : "&") + "Language=" + Language;
}

xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 1 || xmlhttp.readyState == 3) {
src = "http://domain.com/ajax-loader.gif";
document.getElementById("container").innerHTML = "<img style='margin-left:450px; margin-top:15px;' src='" + src + "'>";

}

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("container").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "NameResult.php?" + querystr, true);
xmlhttp.send();
}
</script>

Sherif

2:12 pm on Jun 4, 2011 (gmt 0)

10+ Year Member



Hey Guys,

Any suggestions?

I still didn't find a solution...

The place where it gives the error is from what i had learnt from [w3schools.com ] tutorial

I am not sure what should i do..

Your help will be much appreciated.

Thanks,
Sherif

Fotiman

1:08 pm on Jun 6, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Note, sometimes the lines that IE lists in its error messages are not the lines you think they are. Also, if you're accessing elements within the DOM (document.getElementById('FirstName'), etc.), then this script should be included at the very end of the document, just before the closing </body> tag. I would try moving it there first, and if you still see the error, then I would throw in some alert messages to try and debug exactly where the error is happening.

Sherif

6:09 pm on Jun 6, 2011 (gmt 0)

10+ Year Member



Hey fotiman...

I tried doing what you have mentioned, moving the script to the bottom of the page just before the end of the body tag, and i received an error stating "Object Expected"

However, i tried so alert messages debugging using the try catch command and found the following.

here is what i had done:

Code:
<script type="text/javascript">
function showUser() {

var xmlhttp;
var txt;
try {

if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}

}
catch(err){

txt= "Error= " + err.description;
alert(txt);

}
/*
else {// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
*/
...............Rest of Script...............


To avoid syntax errors, i commented out the else statement as there is no error on it.

I basically moved the declaration of the XMLHttpRequest to the top of the script to avoid any confusion, and added the try catch command to alert me with the error that i receive.

this was the message that i got:
"Error= Object doesn't support this property or method"



For your information, I am testing this on Windows 7 (64-bit) IE8 (8.0.7600.16385)

Other than that, the code seems to be working fine on IE6, firefox, chrome, and safari...


Do you have any suggestions on what i should do?


Thanks a lot for the support.

Sincerely,
Sherif

Fotiman

7:23 pm on Jun 6, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I tried the following very basic test case and did not get any error (Win7 64bit, IE8 8.0.7601.17514, both 32 and 64 bit varieties of IE). Can you tell me if you see an error when you run the following code?


<!DOCTYPE html>
<head>
<title>Test XMLHttpRequest</title>
</head>
<body>
<script>
function showUser() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert('no error');
}
showUser();
</script>
</body>
</html>

Sherif

7:58 pm on Jun 6, 2011 (gmt 0)

10+ Year Member



Hey Fotiman!

when I changed the script to what you had provided, and no alert boxes appear at all...

when i tried it on a safari.. i saw an alert box saying "no error"

Thanks!

Fotiman

8:36 pm on Jun 6, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Interesting, and very strange.
Try this:

<!DOCTYPE html>
<head>
<title>Test XMLHttpRequest</title>
</head>
<body>
<script>
function showUser() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
alert('window.XMLHttpRequest = ' + window.XMLHttpRequest);
xmlhttp = new XMLHttpRequest();
alert('created XMLHttpRequest');
} else { // code for IE6, IE5
alert('Creating ActiveXObject');
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
alert('Created ActiveXObject');
}
alert('no error');
}
showUser();
</script>
</body>
</html>

Essentially just trying to narrow down the problem.

Sherif

11:31 am on Jun 7, 2011 (gmt 0)

10+ Year Member



Hey Fotiman,

I've done what you have said, and here was what i got...

in Safari:
window.XMLHttpRequest = [object XMLHttpRequestConstructor]


however, when I tried it on IE8, this was what i got:

window.XMLHttpRequest = [object XMLHttpRequest]


but i still get an error saying:

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2)
Timestamp: Tue, 7 Jun 2011 10:26:53 UTC


Message: Object doesn't support this property or method
Line: 22
Char: 5
Code: 0
URI: .......URL of Current PAGE.....


<script type="text/javascript">

var xmlhttp;

if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari

alert('window.XMLHttpRequest = ' + window.XMLHttpRequest);

xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

function showUser() {

remaining function code

}
</script>


the bold line is line 22... also I tried moving the request out of the function incase it was a problem, but the problem still seems to exist.

What are your suggestions?

Sincerely,
Sherif

Fotiman

12:41 pm on Jun 7, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



That's really strange. Well, I suppose you could just put this in a try/catch and let IE fall back to the ActiveX version. It would be something like this:

var xmlhttp;
try {
xmlhttp = new XMLHttpRequest();
}
catch (ex) { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}


What that would do is try to create a native XMLHttpRequest object, and if that failed it would then try to create the ActiveX version. However, it sounds to me as though your installation is a bit corrupted, so you may want to do further research to find out why... perhaps even contact Microsoft for support.

Sherif

1:53 pm on Jun 7, 2011 (gmt 0)

10+ Year Member



Fotiman...

As Always! YOU ARE A GENIUS!

I updated my OS (windows 7) tried the code, and the error still appeared..

However, i tried your method (the try catch statement) instead of the if else.. statement, and everything WORKED..

The script is now working on IE8, Safari, Firefox 4

I think it will work on chrome with no problem..

But until now, i do not know why this error happens...

do you have any suggestions?

does this method have any security risks/flaws for my knowledge of which i should be aware of? (the try catch method)


The code now works perfectly fine without showing any errors on IE8.


Thanks for all of the support Fotiman, and as usual.. You're always there to save the day!


Sincerely,
Sherif

Fotiman

6:08 pm on Jun 7, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



The try/catch method doesn't have any security flaws. Essentially what happens is the browser will "try" to do something, and if any errors are thrown it will "catch" them and run whatever code is in your catch block. For example, for browsers that don't have a native XMLHttpRequest (and in your case, IE8 as well for some reason), attempting to create a new XMLHttpRequest object will fail, and so it will then attempt to create the ActiveX version. So the only thing to consider would be if you have any browsers that:
1. Don't have a native XMLHttpRequest object and
2. Don't support ActiveX (any non-IE browser basically)

So you might do something like this:

try {
xmlhttp = new XMLHttpRequest();
}
catch (ex) {
try {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (ex) {
// NO AJAX SUPPORT
}
}