I just can’t make friends with jQuery :)

Hello, there are problems with change . There is a form with a selector city and district. Task: when a user selects a city in the selector, the next asynchronous function should be executed via ajax and php ("Pull out all districts where the area is City = 'city'"), here’s the ajax request:

 $(document).ready(function(){ $("#city").change(function(){var myChoice = $('#city :selected').val(); var data = {myChoice: myChoice} $.ajax({ type: "POST", url: "../blocks/change.php", data: data, dataType: 'json', success: function(data){ var top_list = data.myrowRaion; // содержимое новых элементов var items = "<option>"; // вставляемый html-текст $mylist = $('#raion'); // необходимый список for (var i=0; i< top_list.length; i++) items += top_list[i] + '</option>'; $mylist.append(items); }}); }); }); 

and here is the PHP code:

 <?php include("../blocks/bd.php"); if (isset($_POST['myChoice'])) { $myChoice = $_POST['myChoice']; } if (isset($myChoice)) { $resultRaion = mysql_query("SELECT raion, id FROM raion WHERE idCity = '$myChoice' ", $db); if (!$resultRaion) { echo "<p>Отправьте код на почту san-goldencity@mail.ru:</p>"; exit(mysql_error()); } if (mysql_num_rows($resultRaion) > 0) { $myrowRaion = mysql_fetch_array($resultRaion); } else { echo "<p>Таблицы еще пустые, записей отствует</p>"; exit(); } } $myrowRaion[] = $myrowRaion; echo json_encode($myrowRaion); ?> 

here is the code form:

<select name = "city" id = "city"> <? $ resultCity = mysql_query ("SELECT city, id FROM city", $ db); if (! $ resultCity) {echo "<p> Send an error code to this mail san-goldencity@mail.ru: </ p>"; exit (mysql_error ());}

  if (mysql_num_rows($resultCity) > 0) { $myrowCity = mysql_fetch_array($resultCity); do { printf ("<option value='%s'>%s</option>",$myrowCity["id"], $myrowCity["city"]); } while ($myrowCity = mysql_fetch_array($resultCity)); } else { echo "<p>Таблицы еще пустые, записей отствует</p>"; exit (); } ?> </select> <p class="formP">Район:</p> <select name="raion" id="raion"> <option>Кутузовка</option> <option>Заречка</option> <option>15мкрн</option> <option>новый город</option> </select> 

Help, what am I doing wrong, tell me?

  • Well, please answer somebody) - bemulima
  • Which thread produces an error? - oneboy
  • no at all without action ( - bemulima
  • in bd.php $ _POST ['myChoice'] coming? What is in $ myrowRaion after executing the request? - oneboy
  • and firebug? - oneboy

4 answers 4

Where do you get jquery connected?


  1. I looked at your index.php and saw that you are using both jquery and mootools. You have an error because jquery conflicts with the $ mootools object.

  2. Solution: use jQuery.noConflict

  3. One of the options (by reference to several of them) fixes a TypeError error: $ ("# city") is null:

     jQuery.noConflict(); (function($) { $(function() { $("#city").change(function(){var myChoice = $("#city :selected").val(); 

    .................................................. .................................................. ...

      }); }); })(jQuery); 
  • at the beginning in the tag <head> - bemulima
  • check if the right path to jquery - oneboy
  • the path is correct, the firebug writes here: TypeError: $ ("# city") is null [Interrupt on this error] $ ("# city"). change (function () {var myChoice = $ ('# city: selected') .val (); - bemulima
  • Well, I realized this even when you first wrote ... and I suggest possible options for finding the error ... that would be the whole code of the page on which the form. - oneboy
  • I have a mail ... there is a profile - oneboy
 var top_list = [data.myrowRaion]; // содержимое новых элементов 

Shouldn't it be simple:

 var top_list = data.myrowRaion; // содержимое новых элементов 

In theory, you will succeed

 top_list - [[array from json]] И в итоге top_list[i/*0*/] == data.myrowRaion 

if a

"firebug writes TypeError: $ (" # city ") is null"

you don’t have select with ID city - can you just enter the name?

If you don't want to add an id you can try:

  • see what the answer comes from? if in chrome then F12 and there network - Chad
  • Error 3 on the 3rd line, everything seems to be normal ( - bemulima
  • I do not understand anything, what else is necessary to this fucking code :) ( - bemulima
  • firebug writes TypeError: $ ("# city") is null? - oneboy

So in php code where the request goes instead of

  $resultRaion = mysql_query("SELECT raion, id FROM raion WHERE idCity = 'myChoice' ", $db); 

should probably be

 $resultRaion = mysql_query("SELECT raion, id FROM raion WHERE idCity = '".$myChoice."' ", $db); 

Yes, by the way, and you do not need to secure incoming parameters before sending to SQL ?

In an Ajax request, change var myChoice = $ ('# city: selected'). Val ()


var myChoice = $ ("form select [name = city] option: selected"). val ();

  • I would have to do the task from the beginning without them :) With a sample of the problem, jquery does not see id = "city": (I will do it exactly as you wrote - bemulima
  • Tried did not help - bemulima

Should this code work? Errors at every turn. Let us examine in order, which immediately caught my eye:

1. Getting the value of a select

 $('#city :selected').val(); 

easy enough


2. It is necessary to more easily construct variants of the second select.

 var items = 'option'; $mylist = $('#raion'); //где var?? for (var i=0; i top_list.length; i++) items += top_list[i] + '/option'; //получается только один открывающий option стоит? $mylist.append(items); 

(> <deliberately removed, because the layout moved), it corresponds to:

 for (var i=0; i< top_list.length; i++){ $("<option />", {html: top_list[i]}).appendTo('#raion'); } 

I think it's beautiful :)

3. All this assembly part of the first select.

 if (mysql_num_rows($resultCity) > 0){ $myrowCity = mysql_fetch_array($resultCity); do{ printf ("<option value='%s'>%s</option>",$myrowCity["id"], $myrowCity["city"]); }while ($myrowCity = mysql_fetch_array($resultCity)); }else { echo "<p>Таблицы еще пустые, записей отствует</p>"; exit (); } 

You can rewrite it like this:

 while($myrowCity = mysql_fetch_array($resultCity)) printf ("<option value='%s'>%s</option>",$myrowCity["id"], $myrowCity["city"]); 

4.Here, I did not fully understand. Why is there a list of districts on the form if you wake it up with data from an AJAX request ?:

 <p class="formP">Район:</p> <select name="raion" id="raion"> <option>Кутузовка</option> <option>Заречка</option> <option>15мкрн</option> <option>новый город</option> </select> 

The author, I am by no means against your code, I see that you are only at the beginning of the path, but you should immediately teach yourself to write briefly, succinctly, beautifully. Then the errors will be visible immediately and they will be easily corrected.

  • I tried everything as you wrote, until there are no results (Thanks for the help - bemulima