Solved

jQuery: Spot the difference - one works, one doesn't

Posted on 2009-05-11
19
394 Views
Last Modified: 2012-05-06
I am struggling to understand why some jQuery does not work when something very similar does. The first section of code below works, the second doesn't. The main difference between the two is that in the second section I am querying a database to populate the select menu.
<!-- Example 1 -->

<html>

<head>

	<title>Select Example</title>

	<script type="text/javascript" src="../includes/js/jquery.js"></script>

	<script type="text/javascript">

	$(document).ready(function()

        {

		$("#developer").change(onSelectChange);

	});

	function onSelectChange(){

		var selected = $("#developer option:selected");		

		var output = "";

		if(selected.val() != 0){

			output = "You Selected " + selected.text();

		}

		$("#output").html(output);

	}

	</script>

</head>

<body>

	<h3>Developers</h3>

	<select id="developer">

		<option value="0">Select Developer</option>

		<option value="1">Todd Sharp</option>

		<option value="2">Brian Meloche</option>

		<option value="3">Ray Camden</option>

		<option value="4">Sean Corfield</option>

		<option value="5">Ben Nadel</option>

		<option value="6">Mark Drew</option>	

		<option value="7">Rey Bango</option>	

		<option value="8">Mark Mandel</option>	

		<option value="9">Joe Rinehart</option>

		<option value="10">Dan Vega</option>						

	</select>

	<br /><br />

	<div id="output">

	</div>

</body>

</html>
 
 

<!-- Example 2 -->

<?php

$userPK_rstDocumentZones = "1";

if (isset($_SESSION['MM_Username'])) {

  $userPK_rstDocumentZones = $_SESSION['MM_Username'];

}
 

require_once('../connections/RED_links.php');
 

if (!function_exists("GetSQLValueString")) {

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 

{

  if (PHP_VERSION < 6) {

    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  }
 

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 

  switch ($theType) {

    case "text":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;    

    case "long":

    case "int":

      $theValue = ($theValue != "") ? intval($theValue) : "NULL";

      break;

    case "double":

      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";

      break;

    case "date":

      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";

      break;

    case "defined":

      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;

      break;

  }

  return $theValue;

}

}
 

mysql_select_db($database_RED_links, $RED_links);

$query_rstDocumentZones = sprintf("SELECT zone_pk, zoneTitle FROM zone LEFT JOIN user ON user_pk = %s WHERE zone_pk = 1 OR zone_pk = 2 AND manageZone2 = 1 OR zone_pk = 3 AND manageZone3 = 1 OR zone_pk = 5 AND manageZone5 = 1 OR zone_pk = 6 AND manageZone6 = 1 OR zone_pk = 7 AND manageZone7 = 1 OR zone_pk = 8 AND manageZone8 = 1 OR zone_pk = 9 AND manageZone9 = 1 OR zone_pk = 10 AND manageZone10 = 1 ORDER BY zone_pk ASC", GetSQLValueString($userPK_rstDocumentZones, "int"));

$rstDocumentZones = mysql_query($query_rstDocumentZones, $RED_links) or die(mysql_error());

$row_rstDocumentZones = mysql_fetch_assoc($rstDocumentZones);

$totalRows_rstDocumentZones = mysql_num_rows($rstDocumentZones);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Untitled Document</title>

<script type="text/javascript" src="../includes/js/jquery.js"></script>

<script type="text/javascript">

$(document).ready(function() 

{

	$("#selectDocZone").change(selectVal);

	function selectVal()

	{

		var zoneSelected = $("#selectDocZone option:selected");

		if (zoneSelected.val() != 0)

		{

			$("#selectAdminGroup").removeAttr("disabled");

			$post("getAdminGroups.php", selectDocZone: "zoneSelected");

		}

		else

		{

			$("#selectAdminGroup").attr("disabled", "disabled");

		}

	}

});

</script>

</head>

<body>

<table>

<tr>

	<td>

	<select id="selectDocZone">

		<option value="0">Select a document zone...</option>

		<?php

		do 

		{ ?>

			<option value="<?php echo $row_rstDocumentZones['zone_pk']; ?>"><?php echo $row_rstDocumentZones['zoneTitle']; ?></option>

		<?php } while ($row_rstDocumentZones = mysql_fetch_assoc($rstDocumentZones)); ?>

	</select>

	</td>

	<td>

		<select name="selectAdminGroup" id="selectAdminGroup" disabled="disabled">

			<option value="0">Select an admin group...</option>

		</select>

	</td>

</tr>

</body>

</html>

<?php

mysql_free_result($rstDocumentZones);

?>

Open in new window

0
Comment
Question by:kcalder
  • 10
  • 9
19 Comments
 
LVL 12

Expert Comment

by:alien109
ID: 24357695
you have a url to help with debugging?
0
 

Author Comment

by:kcalder
ID: 24357952
I am running this locally and have put them both up in a browser if that's what you mean. The first works, the second doesn't respond.
0
 
LVL 12

Expert Comment

by:alien109
ID: 24358907
then can you provide the source for the rendered page?
0
 

Author Comment

by:kcalder
ID: 24359091
the source in both cases is as per the code listings I have provided, apart from the jquery source file and the MySql database of course. However, I have tried omitting the repeat region database call and replacing it with a simple option listing as per example 1 but I still can't get it to work.
0
 
LVL 12

Expert Comment

by:alien109
ID: 24359763
what i meant by rendered source was the html output from the php page.
0
 

Author Comment

by:kcalder
ID: 24361690
Sorry, of course. Screen shots below.
grab1.jpg
grab2.jpg
0
 

Author Comment

by:kcalder
ID: 24363575
Sorry again, working too late! The rendered source for both examples is as below...

Example 1 (only html and js so as per the original listing)
<html>
<head>
      <title>Select Example</title>
      <script type="text/javascript" src="../includes/js/jquery.js"></script>
      <script type="text/javascript">
      $(document).ready(function()
      {
            $("#developer").change(onSelectChange);
      });
      function onSelectChange()
      {
            var selected = $("#developer option:selected");            
            var output = "";
            if(selected.val() != 0)
            {
                  output = "You Selected " + selected.text();
            }
            $("#output").html(output);
      }
      </script>
</head>
<body>
      <h3>Developers</h3>
      <select id="developer">

            <option value="0">Select Developer</option>
            <option value="1">Todd Sharp</option>
            <option value="2">Brian Meloche</option>
            <option value="3">Ray Camden</option>
            <option value="4">Sean Corfield</option>
            <option value="5">Ben Nadel</option>

            <option value="6">Mark Drew</option>      
            <option value="7">Rey Bango</option>      
            <option value="8">Mark Mandel</option>      
            <option value="9">Joe Rinehart</option>
            <option value="10">Dan Vega</option>                                    
      </select>
      <br /><br />
      <div id="output">

      </div>
</body>
</html>

Example 2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="../includes/js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
      $("#selectDocZone").change(selectVal);
      function selectVal()
      {
            var zoneSelected = $("#selectDocZone option:selected");
            if (zoneSelected.val() != 0)
            {
                  $("#selectAdminGroup").removeAttr("disabled");
                  $post("getAdminGroups.php", selectDocZone: "zoneSelected");
            }
            else
            {
                  $("#selectAdminGroup").attr("disabled", "disabled");
            }
      }
});
</script>
</head>
<body>
<table>
<tr>
      <td>
      <select id="selectDocZone">            
            <option value="0">Select a document zone...</option>

                              <option value="2">Administration</option>
                              <option value="3">Engineering Process</option>
                              <option value="10">Strategy</option>
                  </select>
      </td>
      <td>
            <select name="selectAdminGroup" id="selectAdminGroup" disabled="disabled">

                  <option value="0">Select an admin group...</option>
            </select>
      </td>
</tr>
</body>
</html>
0
 
LVL 12

Expert Comment

by:alien109
ID: 24363961
To start, let's fix the ajax call. I think this is where you problem is.

Look at the line:
$post("getAdminGroups.php", selectDocZone: "zoneSelected");

To do a post ajax request in jQuery, the correct syntax is:
$.post( url, [data], [callback], [type] )

Not sure what selectDocZone: "zoneSelected" is supposed to be, but I'm assuming it's the data you'd like to pass back to the server? If so, you'll need to do this:

$.post("getAdminGroups.php", {selectDocZone: zoneSelected});
Notice that I've enclosed the data in curly brackets and removed the quotes.

Give that a try...

I'm also assuming you'll want to do something with that data that is returned? If so, you'll need to also supply a callback function for the ajax request.

I'd do so with as follows:

$.post("getAdminGroups.php", {selectDocZone: zoneSelected}, function() {
    // post processing goes here
});
0
 

Author Comment

by:kcalder
ID: 24364008
Thanks, I'll give that a try. In what form does the callback pick up data from the server? How should it be expressed - is it echo'd?
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 12

Expert Comment

by:alien109
ID: 24364027
oops forgot to mention the other change, is case your eyes miss it. You forgot the "." between "$" and "post".

~ cheers
0
 
LVL 12

Accepted Solution

by:
alien109 earned 100 total points
ID: 24364074
whatever is output from the php script, will be picked up in response object. You should actually change the callback function to this:

$.post("getAdminGroups.php", {selectDocZone: zoneSelected}, function(response) {
    // post processing goes here
    alert("response: " + response);
});

The output from the server can be now accessed from the response argument that is passed to the callback.
0
 

Author Comment

by:kcalder
ID: 24364230
Well I modified the code as you suggested and it's working to enable/disable the second select, which is good. But it doesn't appear to be connecting with the server file at all. In answer to your question about the meaning of (now) {selectDocZone: zoneSelected} I am trying to send this key: value pair which represent the current option selected in the select with the id 'selectDocZone'. I am testing it by seeing if selectDocZone is being placed in the $_POST array thus

if (isset($_POST['selectDocZone']))
{
      echo '<script language="javascript" type="text/javascript">
                  <!--
                  alert("$_POST[selectDocZone] is set");
                  //-->
              </script>';
}

but this is not firing.
0
 
LVL 12

Expert Comment

by:alien109
ID: 24364988
What comes back in the response (using the debug alert as I posted above)? Anything? What if you put an else statement on your conditional so that at least something always comes back and you can debug if the client is even making a successful request to the server.

Any way of seeing this on a public server?
0
 

Author Comment

by:kcalder
ID: 24365595
Nothing comes back even when I put an else statement in which indicates that it is not being called. I am receiving no error message about the PHP file not existing or anything.

I'm afraid that I don't have all this on a public server at the moment.
0
 
LVL 12

Expert Comment

by:alien109
ID: 24366528
that says to me you might have a path error, or your php script has an error and is bombing.

what happens if your php script only does this:

<?php
print("test");
?>

does it work then? if not - then we can probably narrow it down to maybe the pathname is incorrect.
0
 

Author Comment

by:kcalder
ID: 24388850
It's definitely odd and I can't work out why it's not connecting. Both the calling file and the php file are in the same folder so there is no pathname as such, but why would it not call it? There's no php at all in the first example so it's not surprising that it works.
0
 

Author Comment

by:kcalder
ID: 24389853
In fact I have other jQuery functions with calls to difference php files located in the same folder and none of them are connecting to their respective php files. So this is bound to be something obvious that I am missing!
0
 

Author Comment

by:kcalder
ID: 24396257
I'm going to award you the points as I think that the jQuery code is working fine now. But I am at a loss as to know why I am getting no response from the php files so I'll have to raise another question on that. Thanks for your perseverance!
0
 
LVL 12

Expert Comment

by:alien109
ID: 24397208
Of course. Glad to help. :)
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

by Julian Matz As of jQuery (http://jquery.com/) 1.4 the .live() method (http://api.jquery.com/live/) supports custom events as well as some standard JavaScript events that it previously didn't support. Among these is the submit event. Unlike …
There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now