Hello. Question: The form on the Ajax at the end when I want to write data to the database is recorded only IDs can not get the names themselves, although they appear in the form. Tell me how to pull them out, but I don’t think in any way most likely some trifle. PS can also tell me in case of an indifferent choice of a country, cities in their field are not replaced but are added.
DB
-- -- База данных: `select` -- -- -------------------------------------------------------- -- -- Структура таблицы `city` -- CREATE TABLE IF NOT EXISTS `city` ( `city_id` int(11) NOT NULL AUTO_INCREMENT, `country_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`city_id`), KEY `country_id` (`country_id`), KEY `country_id_2` (`country_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=31 ; -- -- Дамп данных таблицы `city` -- INSERT INTO `city` (`city_id`, `country_id`, `name`) VALUES (1, 1, 'Киев'), (2, 1, 'Харьков'), (3, 1, 'Львов'), (4, 2, 'Москва'), (5, 2, 'Санкт-Петербург'), (6, 2, 'Белгород'), (7, 3, 'Минск'), (8, 3, 'Брест'), (9, 3, 'Могилев'), (10, 4, 'Стамбул'), (11, 4, 'Анкара'), (12, 4, 'Анталия'), (13, 5, 'Варшава'), (14, 5, 'Краков'), (15, 5, 'Лодзь'), (16, 6, 'Париж'), (17, 6, 'Лион'), (18, 6, 'Кале'), (19, 7, 'Берлин'), (20, 7, 'Лейпциг'), (21, 7, 'Дортмунд'), (22, 8, 'Лондон'), (23, 8, 'Манчестер'), (24, 8, 'Дувр'), (25, 9, 'Вашингтон'), (26, 9, 'Нью-Йорк'), (27, 9, 'Лас-Вегас'), (28, 10, 'Токио'), (29, 10, 'Нагасаки'), (30, 10, 'Хиросима'); -- -------------------------------------------------------- -- -- Структура таблицы `country` -- CREATE TABLE IF NOT EXISTS `country` ( `country_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, PRIMARY KEY (`country_id`), UNIQUE KEY `country_id` (`country_id`), KEY `country_id_2` (`country_id`), KEY `country_id_3` (`country_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ; -- -- Дамп данных таблицы `country` -- INSERT INTO `country` (`country_id`, `name`) VALUES (1, 'Украина'), (2, 'Россия'), (3, 'Белоруссия'), (4, 'Турция'), (5, 'Польша'), (6, 'Франция'), (7, 'Германия'), (8, 'Англия'), (9, 'США'), (10, 'Япония'); -- -------------------------------------------------------- -- -- Структура таблицы `customers` -- CREATE TABLE IF NOT EXISTS `customers` ( `customer_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `country` varchar(255) NOT NULL, `city` varchar(255) NOT NULL, PRIMARY KEY (`customer_id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ; -- -- Дамп данных таблицы `customers` -- INSERT INTO `customers` (`customer_id`, `country`, `city`) VALUES (1, '2', '6'), (2, '1', '1'), (3, '3', '8'); -- -- Ограничения внешнего ключа сохраненных таблиц -- -- -- Ограничения внешнего ключа таблицы `city` -- ALTER TABLE `city` ADD CONSTRAINT `city_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`);
select.js
$("document").ready(function() { getCountry(); function getCountry() { $.ajax({ url: "get_country.php", type: "POST", success: function (data) { data = jQuery.parseJSON(data); $.each(data, function (i, item) { $("#country_id").append('<option value="' + item.country_id + '">' + item.name + '</option>'); }); } }); } getCity(); function getCity(){ $('#country_id').change(function() { var city = $("form").serializeArray(); $.ajax({ url: "get_city.php", type: "POST", data: city, success: function (data) { data = jQuery.parseJSON(data); $.each(data, function (i, item) { $("#city_id").append('<option value="' + item.city_id + '">' + item.name + '</option>'); }); } }); }); } insert(); function insert() { $("#send").click (function () { var form = $("form").serialize(); $.ajax({ url: "insert.php", type: "POST", data:form, success: function (data) { $("#var_dump").html(data); } }); }); } });
conect.php
<?php $db = mysql_connect('localhost','root',''); mysql_select_db('select'); mysql_query("SET NAMES utf-8");
get_country.php
<?php require_once 'conect.php'; $result = mysql_query("SELECT * FROM country ORDER BY country_id"); $country = array(); while($row = mysql_fetch_assoc($result)){ $country[] = $row; } echo json_encode($country);
get_city.php
$country_id = $_POST['country_id']; $result = mysql_query("SELECT * FROM city WHERE country_id = $country_id"); $city = array(); while($row = mysql_fetch_assoc($result)){ $city[] = $row; } echo json_encode($city);
insert.php
<?php require_once 'conect.php'; //mysql_query("INSERT INTO customers (country,city) VALUES ('" . $_POST['country_id'] . "','" . $_POST['city_id'] . "')"); // echo '<pre>'; var_dump($_POST); echo '<pre>';
index.php
<!DOCTYPE html> <head> <title></title> <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/javascript" src="jquery-2.1.4.js"></script> <script type="text/javascript" src="selects.js"></script> <link rel="stylesheet" href="style.css"> </head> <body><br /><br /><br /><br /> <table align="center" > <tr> <td> <form action="#" method="post"> Страна:<br /> <select name="country_id" id="country_id" class="StyleSelectBox"> <option value="0">- выберите город -</option> </select> <br /> Город:<br /> <select name="city_id" id="city_id" class="StyleSelectBox"> <option value="0">- выберите город -</option> </select> <input type="button" id="send" value="Отправить данные"> </form> </td> </tr> </table><br /> <div align="center" id="selectBoxInfo"></div> <p id="var_dump"></p> </body> </html>
select
element, the value of the value attribute of the selected option falls into the form data under the appropriatename
. - Igor