1

So I have a city dropdown which is populated by an onchange, I am trying to get it so that it doesn't require the onchange every time the page reloads, since it is a form.

this is the states dropdown, which works.

<p id=stateDiv><label>State</label></p><p><select name='States' id='States'  onchange='getCity(this.value)'>
            " . $states . "
        </select></p>";

this is the city drop down function call which does not work. I am new to javascript, so I am not sure about how to format a call with php.

if($state==""){   
echo '<p id="citydiv"></p>';
}else{
    echo '<p id="citydiv"><script type="text/javascript">getCity('.$state.');</script></p>';
}

getCity function

function getCity(stateId)
{
  var strURL="findcity.php?state="+stateId;
  var req = getXMLHTTP();
 if (req)
 {
  req.onreadystatechange = function()
  {
    if (req.readyState == 4) // only if "OK"
    {
      if (req.status == 200)
      {
        document.getElementById('citydiv').innerHTML=req.responseText;
       } else {
         alert("There was a problem while using XMLHTTP:\n" + req.statusText);
       }
    }
   }
   req.open("GET", strURL, true);
   req.send(null);
 }
}
2
  • Where is your JavaScript ? Commented Aug 14, 2013 at 21:55
  • 1
    Where's your js and what are you on about? How do you populate your drop down? Why do you need the on change? Commented Aug 14, 2013 at 21:59

2 Answers 2

2

When you get problems like this, ALWAYS look at the HTML source. In this case you might see:

getCity(GA);

Clearly this is wrong, that should be "GA".

Whenever you dump a PHP variable into JavaScript, always use json_encode.

Sign up to request clarification or add additional context in comments.

1 Comment

echo '<p id="citydiv"><script type="text/javascript">getCity('. json_encode($state).');</script></p>'; This did it, Thank you.
1

Along with what Kolink said, what does your javascript function "getCity" look like? If it is just returning a value, this will not work. You will either need to grab the element (document.getElementById('cityDiv')) and set the innerHTML to the return value OR use document.write instead of returning a value.

1 Comment

I just included it, I have it set this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.