Форум программистов, компьютерный форум, киберфорум
PHP: базы данных
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.58/19: Рейтинг темы: голосов - 19, средняя оценка - 4.58
0 / 0 / 0
Регистрация: 09.02.2014
Сообщений: 2

Передача данных в php через ajax

09.02.2014, 12:37. Показов 3919. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Друзья помогите !!! У меня тут возникла проблема с передачей данных в php скрипт

вот php файл
PHP
1
2
3
4
5
6
7
8
9
10
11
12
<?php
    $db_hostname = 'localhost';
    $db_database = 'mygame';
    $db_username = 'root';
    $db_password = '';
    $login = $_POST['login'];
    $password = $_POST['password'];
    $db_server = mysql_connect($db_hostname,$db_username,$db_password);
    mysql_select_db($db_database) or die("Error :" . mysql_error());
    $query = "INSERT INTO users VALUES('$login','$password')";
    $result=mysql_query($query);    
?>
а вот javaScript
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function addUser () {
    var name = document.getElementById('name').value;
    var password = document.getElementById('password').value;
    var xhttp;
    var url="registration.php";
 
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        document.getElementById('showmini').innerHTML=xhttp.responseText;
    }
 
    xhttp.open('POST',url,true);
    xhttp.send();
    
}
Где и как передать name и password
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
09.02.2014, 12:37
Ответы с готовыми решениями:

Передача данных через разделяемую память, сервер на C++ клиент на PHP
Здравствуйте коллеги! Помогите решить задачку: Есть сервер написанный на C++ и клиент написанный на PHP. Сервер записывает данные в...

Передача массива из input PHP + AJAX
Приветствую! Передаю массив из формы через ajax &lt;script type=&quot;text/javascript&quot;&gt; function saveopt() { var id =...

Передача массива из JavaScript(AJAX, JSON) в PHP
Добрый вечер! Ребят, тут такое дело, имеется схема зала с местами. У каждого места есть свой ID. По клику мы запоминаем ID (не больше...

3
Автор FAQ
 Аватар для insideone
3687 / 964 / 114
Регистрация: 10.01.2010
Сообщений: 2,550
14.02.2014, 01:54
Пользоваться jQuery нельзя?

JavaScript
1
2
3
4
5
6
7
8
9
jQuery(function($) {
    var name = document.getElementById('name').value;
    var password = document.getElementById('password').value;
    var url="registration.php";
 
    $.post(url, {login: name, password: password}, function () {
            alert('Запрос завершён');
    });
});
0
0 / 0 / 0
Регистрация: 13.02.2014
Сообщений: 5
14.02.2014, 12:46
Код JS
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function obj(a1,a2){
 
this.name=a1;
this.password=a2;
}
 
function addUser () {
    var name = document.getElementById('name').value;
    var password = document.getElementById('password').value;
    
     var name_pass=new  obj(name,password);
             // Сериализация в JSON-формируем джейсоновскую строку-для отправки серверу
             var jsonData = JSON.stringify(name_pass);
             var req = getXmlHttpRequest();
                    req.onreadystatechange = function()//поскольку мы предполагаем асинхронный запрос-то сдесь у нас onreadystatechange ловит присланные с сервера данные
                {
                    if (req.readyState != 4) { return;}//если не пришел ответ с сервера то выходим
                    //если ответ с сервера пришел,то:
                    var restext=document.getElementById('showmini');
                    var text=req.responseText;
                    restext.innerHTML=text;
                  
                }
            
               req.open("POST", "папка в которой файл php/название вашего php файла.php", true);//готовим асинхронный запрос
              req.setRequestHeader("Content-Type", "text/plain");//эти два заголовка при методе POST запроса  обязательны
              req.setRequestHeader("Content-Length", jsonData.length);          
              req.send(jsonData);   //тело сообщения серверу-это наша джейсоновская строка
}
Код php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?php
    $db_hostname = 'localhost';
    $db_database = 'mygame';
    $db_username = 'root';
    $db_password = '';
    $login = $_POST['login'];
    $password = $_POST['password'];
    $db_server = mysql_connect($db_hostname,$db_username,$db_password);
    mysql_select_db($db_database) or die("Error :" . mysql_error());
     
 
 
 
$rawPost = file_get_contents('php://input');
// Заголовки ответа
header('Content-type: text/plain; charset=utf-8');
header('Cache-Control: no-store, no-cache');//отменяем кэширование
 
// Если данные были переданы...
if ($rawPost)
{
$record = json_decode($rawPost);//разбираем джейсоновский пакет в объект
 
 
if((isset($record->name))&&(isset($record->password))){
$login=$record->name;
$password=$record->password;
 
 
$query = "INSERT INTO users VALUES('$login','$password')";
  $result=mysql_query($query); 
  
  
}
?>
В html прикрепляем файлы
HTML5
1
2
<script type="text/javascript" src="xmlhttprequest.js"></script>
<script type="text/javascript" src="json2.js"></script>
xmlhttprequest.js
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
** Функция возвращат объект XMLHttpRequest
*/
function getXmlHttpRequest()
{
    if (window.XMLHttpRequest) 
    {
        try 
        {
            return new XMLHttpRequest();
        } 
        catch (e){}
    } 
    else if (window.ActiveXObject) 
    {
        try 
        {
            return new ActiveXObject('Msxml2.XMLHTTP');
        } catch (e){}
        try 
        {
            return new ActiveXObject('Microsoft.XMLHTTP');
        } 
        catch (e){}
    }
    return null;
}
json2.js
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/*
    json2.js
    2007-11-06
 
    Public Domain
 
    No warranty expressed or implied. Use at your own risk.
 
    See [url]http://www.JSON.org/js.html[/url]
 
    This file creates a global JSON object containing two methods:
 
        JSON.stringify(value, whitelist)
            value       any JavaScript value, usually an object or array.
 
            whitelist   an optional that determines how object values are
                        stringified.
 
            This method produces a JSON text from a JavaScript value.
            There are three possible ways to stringify an object, depending
            on the optional whitelist parameter.
 
            If an object has a toJSON method, then the toJSON() method will be
            called. The value returned from the toJSON method will be
            stringified.
 
            Otherwise, if the optional whitelist parameter is an array, then
            the elements of the array will be used to select members of the
            object for stringification.
 
            Otherwise, if there is no whitelist parameter, then all of the
            members of the object will be stringified.
 
            Values that do not have JSON representaions, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped, in arrays will be replaced with null. JSON.stringify()
            returns undefined. Dates will be stringified as quoted ISO dates.
 
            Example:
 
            var text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'
 
        JSON.parse(text, filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.
 
            The optional filter parameter is a function that can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.
 
            Example:
 
            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.
 
            myData = JSON.parse(text, function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });
 
    This is a reference implementation. You are free to copy, modify, or
    redistribute.
 
    Use your own copy. It is extremely unwise to load third party
    code into your pages.
*/
 
/*jslint evil: true */
/*extern JSON */
 
if (!this.JSON) {
 
    JSON = function () {
 
        function f(n) {    // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }
 
        Date.prototype.toJSON = function () {
 
// Eventually, this method will be based on the date.toISOString method.
 
            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };
 
 
        var m = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };
 
        function stringify(value, whitelist) {
            var a,          // The array holding the partial texts.
                i,          // The loop counter.
                k,          // The member key.
                l,          // Length.
                r = /["\\\x00-\x1f\x7f-\x9f]/g,
                v;          // The member value.
 
            switch (typeof value) {
            case 'string':
 
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe sequences.
 
                return r.test(value) ?
                    '"' + value.replace(r, function (a) {
                        var c = m[a];
                        if (c) {
                            return c;
                        }
                        c = a.charCodeAt();
                        return '\\u00' + Math.floor(c / 16).toString(16) +
                                                   (c % 16).toString(16);
                    }) + '"' :
                    '"' + value + '"';
 
            case 'number':
 
// JSON numbers must be finite. Encode non-finite numbers as null.
 
                return isFinite(value) ? String(value) : 'null';
 
            case 'boolean':
            case 'null':
                return String(value);
 
            case 'object':
 
// Due to a specification blunder in ECMAScript,
// typeof null is 'object', so watch out for that case.
 
                if (!value) {
                    return 'null';
                }
 
// If the object has a toJSON method, call it, and stringify the result.
 
                if (typeof value.toJSON === 'function') {
                    return stringify(value.toJSON());
                }
                a = [];
                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {
 
// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
 
                    l = value.length;
                    for (i = 0; i < l; i += 1) {
                        a.push(stringify(value[i], whitelist) || 'null');
                    }
 
// Join all of the elements together and wrap them in brackets.
 
                    return '[' + a.join(',') + ']';
                }
                if (whitelist) {
 
// If a whitelist (array of keys) is provided, use it to select the components
// of the object.
 
                    l = whitelist.length;
                    for (i = 0; i < l; i += 1) {
                        k = whitelist[i];
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                } else {
 
// Otherwise, iterate through all of the keys in the object.
 
                    for (k in value) {
                        if (typeof k === 'string') {
                            v = stringify(value[k], whitelist);
                            if (v) {
                                a.push(stringify(k) + ':' + v);
                            }
                        }
                    }
                }
 
// Join all of the member texts together and wrap them in braces.
 
                return '{' + a.join(',') + '}';
            }
        }
 
        return {
            stringify: stringify,
            parse: function (text, filter) {
                var j;
 
                function walk(k, v) {
                    var i, n;
                    if (v && typeof v === 'object') {
                        for (i in v) {
                            if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                                n = walk(i, v[i]);
                                if (n !== undefined) {
                                    v[i] = n;
                                }
                            }
                        }
                    }
                    return filter(k, v);
                }
 
 
// Parsing happens in three stages. In the first stage, we run the text against
// regular expressions that look for non-JSON patterns. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we want to reject all
// unexpected forms.
 
// We split the first stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace all backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
 
                if (/^[\],:{}\s]*$/.test(text.replace(/\\./g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
 
// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
 
                    j = eval('(' + text + ')');
 
// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.
 
                    return typeof filter === 'function' ? walk('', j) : j;
                }
 
// If the text is not JSON parseable, then a SyntaxError is thrown.
 
                throw new SyntaxError('parseJSON');
            }
        };
    }();
}
0
0 / 0 / 0
Регистрация: 09.02.2014
Сообщений: 2
14.02.2014, 13:04  [ТС]
Всем спасибо все получилось
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
14.02.2014, 13:04
Помогаю со студенческими работами здесь

Ajax передача данных в форму
Помогите пожалуйста, 2 дня потратил, все равно корректно не работает. Имеется несколько десятков форм следующего вида: &lt;form...

Передача данных из одного php скрипта в другой php скрипт
Работаю с методом API. Метод может передать данные только в один скрипт. А уж из этого скрипта я хочу передать данные во все остальные...

Отправка данных в базу данных php+ajax
Здраствуйте, я хочу дание с двух полей форми обновлять в базе даних с помощью ajax, тоисть у меня есть таблица с двумя полями и есть форма...

Не работают некоторые запросы в БД из PHP через AJAX с HTML страницы
Делаю сайт отеля, где есть возможность сложного поиска по номерам отеля, который кстати говоря работает полностью. А также возможность в...

Как отправить json через ajax на php для записи в БД?
здравствуйте подскажите пожалуйста как отправить через ajax json где в нем хранится ид товара плюс количество, отправить на PHP для...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек SDL3 и Box2D из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия SDL 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual. . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru