2016-01-04 2 views
1

Мой php работает, но по какой-то причине мои переменные не передаются. Что я делаю неправильно? Я пытаюсь передать сообщение через ajax, и я, похоже, не могу получить сообщение об ошибке или сообщении о успехе, независимо от того, где я помещаю его в свой php .., который заставляет меня думать, что проблема лежит внутри моего ajax/javascript. Ajax должен помещать сообщение прямо в определенное. Я также понимаю, что это было задано ранее здесь, но я действительно посмотрел на многие из них и до сих пор не могу понять, что случилось. Спасибо, ребята, извините за стену.Как мне вернуть ошибки формы

AJAX

<!-- Email --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<script> 
    // magic.js 
    $(document).ready(function() { 

    // process the form 
    $('form').submit(function(event) { 
     $('#sub_result').html(""); 

     // get the form data 
     // there are many ways to get this data using jQuery (you can use the class or id also) 
     var formData = { 
      'email'    : $('input[name=email]').val(), 
     }; 

     // process the form 
     $.ajax({ 
      type  : 'POST', // define the type of HTTP verb we want to use (POST for our form) 
      url   : 'phEmail.php', // the url where we want to POST 
      data  : formData, // our data object 
      dataType : 'json', // what type of data do we expect back from the server 
      encode  : true 
     }) 
      // using the done promise callback 
      .done(function(data) { 

       // log data to the console so we can see 
       console.log(data); 

       // here we will handle errors and validation messages 
       if (! data.success) { 

        // handle errors for email --------------- 
        if (data.errors.email) { 
         $('#sub_result').addClass('class="error"'); // add the error class to show red input 
         $('#sub_result').append('<div class="error">' + data.errors.email + '</div>'); // add the actual error message under our input 
        } 



       } else { 

        // ALL GOOD! just show the success message! 
        $('#sub_result').append('<div class="success" >' + data.message + '</div>'); 

        // usually after form submission, you'll want to redirect 
        // window.location = '/thank-you'; // redirect a user to another page 

       } 
      }) 

      // using the fail promise callback 
      .fail(function(data) { 

       // show any errors 
       // best to remove for production 
       console.log(data); 
      }); 

     // stop the form from submitting the normal way and refreshing the page 
     event.preventDefault(); 
    }); 

    }); 
</script> 

PHP

<?php 
$errors = array();  // array to hold validation errors 
$data = array(); // array to pass back data 
// validate the variables ====================================================== 
// if any of these variables don't exist, add an error to our $errors array 

if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false) 
{ 
    $errors['email'] = 'Email is not valid'; 
} 


if (empty($_POST['email'])){ 
$errors['email'] = 'Email is required.'; 
} 
// if there are items in our errors array, return those errors============================ 
if (! empty($errors)) { 
$data['success'] = false; 
$data['errors'] = $errors; 


} else { 

//variables=============================================================================== 
$servername = "localhost"; 
$username = "ghostx19"; 
$password = "nick1218"; 
$dbname = "ghostx19_samplepacks"; 
$user = $_POST['email']; 
// Create connection====================================================================== 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    echo "Connection failed"; 
} 
//add user================================================================================ 
$sql = "INSERT INTO users (email) 
VALUES ('$user')"; 
if ($conn->query($sql) === TRUE) { 
    $data['success'] = true; 
    $data['message'] = 'Subscribed!'; 
} else { 
    $errors['email'] = 'Error'; 
} 
$conn->close(); 


// message to me========================================================================== 
$to  = '[email protected]'; 
$subject = 'New subscription'; 
$message = $_POST['email']; 
$headers = 'From: [email protected]' . "\r\n" . 
    'Reply-To: [email protected]'; 
mail($to, $subject, $message, $headers); 
//message to user========================================================================= 
$to  = $_POST['email']; 
$subject = 'Subscribed!'; 
$message = 'Hello new member, 
    Thank you for becoming a part of samplepackgenerator.com. You are now a community member and will recieve light email updates with the lastest information. If you have recieved this email by mistake or wish to no longer be apart of this community please contact [email protected] 
    Cheers!, 
    -Nick Garver '; 
$headers = 'From: [email protected]' . "\r\n" . 
    'Reply-To: [email protected]'; 
mail($to, $subject, $message, $headers); 
// show a message of success and provide a true success variable========================== 
$data['success'] = true; 
$data['message'] = 'Subscribed!'; 
} 
?> 

HTML

<!-- Subscription --> 
    <div class="container shorter"> 
    <div class="no-result vertical-align-outer"> 
     <div class="vertical-align"> 
     <form action="phEmail.php" method="POST"> 
      <!-- EMAIL --> 
      <div id="email-group" class="form-group"> 
      <label for="email"></label> 
      <input type="text" class="email" name="email" placeholder="Enter your email"> 
      <button type="submit" class="emailbtn">Subscribe</button> 
      <span></span> 
      <!-- errors --> 
      </div> 
      </div> 
     </div> 
     </div> 
      <br> 
      <br> 
      <div id="sub_result"> 
      </div> 
+0

Использовать json encode в php и получить результат json в ответе ajax – devpro

ответ

1

Вам просто нужно использовать json_encode в вашем PHP becuase типа данных является JSON и вы ожидаете ответ в формате JSON, как этот

if (!empty($error)){ 

// your stuff 

$data['success'] = false; 
$data['errors'] = $errors; 
echo json_encode($data); 
} 
else { 
// your stuff 
$data['success'] = "SUCCESS MESSAGE"; 
$data['errors'] = false; 
echo json_encode($data); 
} 
+1

ты лучший –

0

РНР не возвращает никакого значения, добавьте простой "эхо" линии в конце:

... 
$data['success'] = true; 
$data['message'] = 'Subscribed!'; 
} 
echo $data['message']; 
?> 

И в js (если все остальные коды верны), вы получите сообщение.

+0

Другим типом данных является json и OP с использованием data.success в ajax succes и т. Д. – devpro

1

Это потому, что вы забыли кодировать массив $data. Сделайте echo json_encode($data); непосредственно перед окончанием PHP тегом (?>), как это:

// your code 

    mail($to, $subject, $message, $headers); 
    // show a message of success and provide a true success variable========================== 
    $data['success'] = true; 
    $data['message'] = 'Subscribed!'; 
    } 
    echo json_encode($data); 
?> 
+0

Да, это правильный путь. :) – devpro

+0

Поскольку эхо находится на последней строке кода, все в порядке, но я предпочитаю использовать exit (json_encode ($ data)); так как в вашем ответе вам не нужен какой-либо другой вывод (по следующему коду). –

+0

@dnFer Я не думаю, что 'exit()' необходимо здесь, потому что после 'echo json_encode ($ data);' скрипт завершается в любом случае. –

0

Ваш php-файл ничего не отправляет на выход.

Добавить строку exit(json_encode($data)); в ваш файл php на строке, где вы хотите вернуть свой ответ.