I am in JS and ajax is not strong, I ask for help. Task: there is an input field input, and when changing the text in it, a new query should be made to the database, and the sample should be based on the entered text in the field, I try to do this:

$('#street').on('input keyup', function(e) { var name_st = this.value; <? $sql_streetj = mysql_fetch_assoc(mysql_query("SELECT * FROM `street` WHERE `name_ru` = 'ТУТ ЗНАЧЕНИЕ ПЕРЕМЕННОЙ ИЗ name_st'")); $sl2 = array(); $all_city_db2 = mysql_query("SELECT * FROM `houses` WHERE `id_street` = '$sql_streetj[id]'"); while ($city_name_ru2 = mysql_fetch_assoc($all_city_db2)) { $sl2[] = $city_name_ru2['name_ru']; } ?> }); 

I can't insert the value of a variable from JS: name_st , everything should happen without reloading the page. I would be very grateful for the help!

  • Well, make a request to the server on which php. api.jquery.com/jquery.ajax ps and <? worth writing as <?php - Naumov
  • @Naumov you're sorry, but I did not understand. How can this be combined with my code? I have everything on one page - iKey
  • code var name_st = this.value; is executed on the client by the browser, and the code between <? ... ?> <? ... ?> - on the server. - Igor
  • @Igor maybe there are some good examples? I just sat at the computer today looking for a solution to this problem, which I probably don’t see the obvious - iKey
  • Okay, let's start with the basics. Does the server have php code running? - Naumov

1 answer 1

As a javascript function, you cannot call PHP! To do this, use ajax, you need to send the value received in JS to the php file that will process your request and send a response

Js

 $('#street').on('input keyup', function(e) { var name_st = this.value; j.ajax( { type: 'POST', url: 'url обработчика php', data: {info:name_st}, 'success' : function (result) { console.log(result); } }); }); 

Php

 <?php if(isset($_POST['info'])){ $sql_streetj = mysql_fetch_assoc(mysql_query("SELECT * FROM `street` WHERE `name_ru` = '".$_POST['info']."' ")); $sl2 = array(); $all_city_db2 = mysql_query( "SELECT * FROM `houses` WHERE `id_street` = '$sql_streetj[id]'" ); while ($city_name_ru2 = mysql_fetch_assoc($all_city_db2)) { $sl2[] = $city_name_ru2['name_ru']; } } ?> 
  • minus for the fact that you, too, did not write the code correctly: D inhale it in order, please, and change it. - Naumov
  • I'm not guilty)) your editor is buggy! ) - Arsen
  • Yes, and where is the editor I'm about the key points - Naumov
  • Do not make changes I will correct everything myself - Naumov
  • @Naumov crap but I can't agree with the editor)) deletes the floor of the code)) can I not do it? - Arsen