За последние 24 часа нас посетили 16907 программистов и 1646 роботов. Сейчас ищут 937 программистов ...

Как узнать переменную

Тема в разделе "JavaScript и AJAX", создана пользователем Blofield, 10 сен 2013.

  1. Blofield

    Blofield Активный пользователь

    С нами с:
    10 сен 2013
    Сообщения:
    3
    Симпатии:
    0
    Здравствуйте. Помогите пожалуйста с кодом. Есть форма заказа товара на сайте:

    Код (Text):
    1. <form id="form1" > 
    2.  
    3. <label class="label_to" style="display:none;">Верхняя форма</label>
    4. <a goal="true" style="display:none;" href="#" onclick="yaCounter22142846.reachGoal('ORDER'); return false;"></a>
    5. <a goal="true" style="display:none;" href="#" onclick="ga('send', {'hitType': 'event','eventCategory': 'ORDER','eventAction': 'ORDER','eventLabel': 'ORDER', 'eventValue': 1}); return false;"></a>
    6. <label class="label_sndok" style="display:none;color:#FFFAFA;">Спасибо!<br /> Ваша заявка принята. <br /> Наш менеджер свяжется с Вами в ближайшее время!
    7. </label>
    8. <div class="progressimg" style="display:none;"><img src="ap_s/img/loader.gif" border="0"></div>
    9. <!-- елементы формы -->
    10. <input class="form-field " type="text" value="Ваше имя..." defval="Ваше имя...">
    11. <input class="form-field " value="Ваш телефон..." sname="Введите телефон..." defval="Ваш телефон..." require="true" vphone="true" title="Это поле обязательно для заполнения" type="text"/>
    12. <input type="button" class="button1" value=" " onclick="pushmsg(this);" />
    13. <!-- Конец елементы формы -->
    14. </form>
    Данные обрабатываются скриптом:

    Код (Text):
    1. var r = preload('ap_s/img/hover.png,ap_s/img/normal.png,ap_s/img/active.png');
    2.  
    3. function _onfocus(event){
    4. cheak_edit(event);
    5. }
    6.  
    7. function _onblur(event){
    8. cheak_edit(event);
    9. }  
    10.  
    11. function cheak_edit(event){
    12. if ($('#'+event.id).attr('defval') != null)
    13. if (event.value.length!=0){
    14. if (event.value != $('#'+event.id).attr('defval')){
    15. $("#"+event.id).addClass('edit_f_te');
    16. }else{
    17. $('#'+event.id).val("");
    18. $("#"+event.id).addClass('edit_f_te');
    19. }
    20. }else {
    21. $('#'+event.id).val($('#'+event.id).attr('defval'));
    22. $("#"+event.id).removeClass('edit_f_te');
    23. }
    24. $('#'+event.id).removeClass('edit_f_error');
    25. }
    26.  
    27.  
    28. function pushmsg(event) {
    29. var str = 'p=1';
    30. var sform=''; var ft='';
    31. var v = 0;
    32. $(event).parents('form').each(function(){
    33. sform = $(this).attr('id');
    34. });
    35.  
    36. // vemail="true"
    37. $('#'+sform).find("input[vemail*='true']").each(function(){
    38. if (validate($(this).val())==false){
    39. $(this).addClass('edit_f_error');
    40. v = 1;
    41. }
    42. });
    43.  
    44. $('#'+sform).find("input[vphone='true']").each(function(){
    45. if (validatephone($(this).val())==false){
    46. $(this).addClass('edit_f_error');
    47. v = 1;
    48. }
    49. });
    50.  
    51. $('#'+sform).find("input[type='text'], textarea").each(function(){
    52. str += "&" + $(this).attr('id')+'='+encodeURIComponent(
    53. (($(this).attr('sname')!=null)?$(this).attr('sname'):$(this).attr('defval'))
    54. +':;:'+$(this).val());
    55. if (($(this).attr('defval')==$(this).val()) && ($(this).attr('require')!=null)){
    56. $(this).addClass('edit_f_error');
    57. v = 1;
    58. }
    59. });
    60.  
    61. if (v==1) return;
    62.  
    63. ft = $('#'+sform).find('.label_to').text();
    64.  
    65. $('#'+sform).children().hide();
    66. $('#'+sform).find(".progressimg").show();
    67.  
    68.  
    69. str += "&tmes=" + encodeURIComponent(ft);
    70.  
    71.  
    72. $.ajax({
    73. url: "ap_s/apushmsg.php",
    74. data: str,
    75. dataType: "xml",
    76. type: "POST",
    77. success: function (data, textStatus) {
    78. $(data).find('status').each(function () {
    79. if ($(this).attr('error')=="0"){
    80. $('#'+sform).find(".progressimg").hide();
    81. $('#'+sform).find('.label_sndok').show();
    82. $('#'+sform).find('a[goal="true"]').each(function(){
    83. $(this).click();
    84. });
    85. }
    86. else {
    87. $('#'+sform).find('.label_sndok').show();
    88. }  
    89.  
    90. });
    91. },
    92. error:
    93. function (request, status, error) {
    94. alert('Error!');//alert(request.responseText);
    95. }
    96. /*   function () {
    97. alert('Error!');
    98. }*/
    99. });
    100. }
    101.  
    102. function preload(images) {
    103. if (document.images) {
    104. var i = 0;
    105. var imageArray = new Array();
    106. imageArray = images.split(',');
    107. var imageObj = new Image();
    108. for(i=0; i<=imageArray.length-1; i++) {
    109. imageObj.src=imageArray[i];
    110. }
    111. }
    112. }
    113.  
    114. function validate(address) {
    115. var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    116. if(reg.test(address) == false) {
    117. return false;
    118. }
    119. return true;
    120. }
    121.  
    122.  
    123. function validatephone(phone) {
    124. var reg = /^[-()\s\d]+$/
    125. return reg.test(phone);
    126. }  
    127.  
    128.  
    129.  
    130. function generateGuid() {
    131. var result, i, j;
    132. result = '';
    133. for(j=0; j<32; j++) {
    134. if( j == 8 || j == 12|| j == 16|| j == 20)
    135. result = result + '-';
    136. i = Math.floor(Math.random()*16).toString(16).toUpperCase();
    137. result = result + i;
    138. }
    139. return result;
    140. }
    141.  
    142.  
    143. function bmf(){
    144.  
    145. $("form").each(function(){
    146. $(this).find("input[type='text'], textarea").bind('focus', function() {
    147. _onfocus(this);
    148. });
    149.  
    150. $(this).find("input[type='text'], textarea").bind('blur', function() {
    151. _onblur(this);
    152. });
    153.  
    154. $(this).find('*').each(function(){
    155. if ($(this).attr('id')==null){
    156. $(this).attr('id',generateGuid() );
    157. }
    158. });
    159. $(this).find("input[type='text'], textarea").each(function(){
    160. if ($(this).attr('sname')==null){
    161. $(this).attr('sname',$(this).attr('defval'));
    162. }
    163. });
    164. });
    165. }
    166.  
    167. function init_forms(){
    168. bmf();
    169. }
    170.  
    171. $(function(){
    172. init_forms();
    173.  
    174. });
    Из скрипта хочу передать данные формы в php и отправить на мыло:

    Код (Text):
    1. <?php
    2.  
    3. $text = $_GET['str'];
    4.  
    5. $address = "";
    6.  
    7. $verify = mail($address,"Zakaz",$text,"Content-type:text/plain; Charset=windows-1251\r\n");
    8.  
    9. ?>
    Письмо отправляется, но пустое. Подскажите пожалуйста, где ошибка.
     
  2. Fell-x27

    Fell-x27 Суперстар
    Команда форума Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.156
    Симпатии:
    1.771
    Адрес:
    :сердА
     
  3. Blofield

    Blofield Активный пользователь

    С нами с:
    10 сен 2013
    Сообщения:
    3
    Симпатии:
    0
    изменил на POST:

    Код (Text):
    1.  
    2. $text = $_POST['str'];
    Все равно пустое письмо
     
  4. Fell-x27

    Fell-x27 Суперстар
    Команда форума Модератор

    С нами с:
    25 июл 2013
    Сообщения:
    12.156
    Симпатии:
    1.771
    Адрес:
    :сердА
    а сдается мне, что у вас там нет элемента такого 'str'. По крайней мере в формировании переменной имя элемента формируется исходя из id в html-ке. Выведите в файл куда-нибудь содержимое $_REQUEST, либо надо ajax попроавить временно, чтобы показывал ответ сервера. В общем узнать, что точно у вас передается от клиента.
     
  5. Blofield

    Blofield Активный пользователь

    С нами с:
    10 сен 2013
    Сообщения:
    3
    Симпатии:
    0
    Спасибо за помощь, сам понимаю, что не могу передать переменную в php, но не знаю как определить. Не подскажешь как вывести в файл?
     
  6. smitt

    smitt Старожил

    С нами с:
    3 янв 2012
    Сообщения:
    3.166
    Симпатии:
    65
    Код (PHP):
    1. file_put_contents('file_name', print_r($_REQUEST, true)); 
     
  7. willyhaase

    willyhaase Новичок

    С нами с:
    28 ноя 2013
    Сообщения:
    1
    Симпатии:
    0
    Blofield, у Вас получилось решить проблему? А то у меня аналогичная, приходят пустые сообщения.