0

I've downloaded a template for web.

In this template, there is a php script to send email. In this script there is a validate() function, in which there is a variable $return_array. one of its value is $return_array['success'] that could be '0' or '1'. In another file, a javascript one, there is a click() function, that manages the value of 'success' in the php script doing if(html.success == '1')...but it does not work as expected, infact it is always '0'...what do I need to check?

Here is the html form:

<form method="POST" action="send_form_email.php" id="contactform">
            <div>
                <label for="name" style="color:white;">Inserisci il tuo nome</label>
                    <input type="text" class="input-field" id="name" name="name" value="">
            </div>
            <div>
                <label for="email" style="color:white;">Inserisci la tua e-mail</label>
                    <input type="text" class="input-field" id="email" name="email" value="">
            </div>
            <div>
                <label style="color:white;">Scrivi il tuo messaggio</label>
                    <textarea id="message" name="message" style="min-height: 160px;"></textarea>
            </div>                  
                <a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Invia E-Mail</a>
                <div id="success">Il tuo messaggio &egrave stato inviato correttamente!</div>
                <div id="error">Impossibile inviare il messaggio. Riprovare pi&ugrave tardi.</div>
        </form>

and here is the function into the php

<?php 
// EDIT THE 2 LINES BELOW AS REQUIRED
$send_email_to = "[email protected]";
$email_subject = "Feedback subject";
function send_email($name,$email,$email_message)
{
  global $send_email_to;
  global $email_subject;
  $headers = "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
  $headers .= "From: ".$email. "\r\n";
  $message = "<strong>Email = </strong>".$email."<br>";
  $message .= "<strong>Name = </strong>".$name."<br>";  
  $message .= "<strong>Message = </strong>".$email_message."<br>";
  @mail($send_email_to, $email_subject, $message,$headers);
  return true;
}

function validate($name,$email,$message)
{
  $return_array = array();
  $return_array['success'] = '1';
  $return_array['name_msg'] = '';
  $return_array['email_msg'] = '';
  $return_array['message_msg'] = '';
  if($email == '')
  {
    $return_array['success'] = '0';
    $return_array['email_msg'] = 'email is required';
  }
  else
  {
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    if(!preg_match($email_exp,$email)) {
      $return_array['success'] = '0';
      $return_array['email_msg'] = 'enter valid email.';  
    }
  }
  if($name == '')
  {
    $return_array['success'] = '0';
    $return_array['name_msg'] = 'name is required';
  }
  else
  {
    $string_exp = "/^[A-Za-z .'-]+$/";
    if (!preg_match($string_exp, $name)) {
      $return_array['success'] = '0';
      $return_array['name_msg'] = 'enter valid name.';
    }
  }

  if($message == '')
  {
    $return_array['success'] = '0';
    $return_array['message_msg'] = 'message is required';
  }
  else
  {
    if (strlen($message) < 2) {
      $return_array['success'] = '0';
      $return_array['message_msg'] = 'enter valid message.';
    }
  }
  return $return_array;
}

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];


$return_array = validate($name,$email,$message);

if($return_array['success'] == '1')
{
    send_email($name,$email,$message);

}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>

and following the javascript code:

$('#button-send').click(function(event){
    $('#button-send').html('Invio in corso...');
    event.preventDefault();

    //$('html, body').scrollTo( $('#contact'), 'fast' );
    $.ajax({
        type: 'POST',
        url: 'send_form_email.php',
        data: $('#contactform').serialize(),
        success: function(html) {
            if(html.success == '1')
            {
                $('#button-send').html('Invia E-Mail');
                $('#success').show();

            }
            else
            {
                $('#button-send').html('Invia E-Mail');
                $('#error').show();
                console.log(html);
            }                   
        },
        error: function(){
            $('#button-send').html('Invia E-Mail');
            $('#error').show();
            console.log("not html.success");
        }
    });

});

EDIT:

I've edited the php part adding at the end the json_encode and content type, but when there is an error, like name missing or mail missing, I expect to see something appears near the input form, but it does not...

4
  • parse success return data first then match Commented Oct 8, 2014 at 9:56
  • Try json_encode your return array and use the json in your ajax success Commented Oct 8, 2014 at 9:56
  • html=$.parseJSON(html); then use html['Success'] instead of html.success Commented Oct 8, 2014 at 10:04
  • where do I need to add html=$.parseJSON(html); ?I've added it before the if(html['success']) but it gives me the error "html is null" Commented Oct 8, 2014 at 11:57

1 Answer 1

1

Use return json_encode($return_array); Instead of return $return_array;.

Json encode returns key => value pair array .

Also use dataType: "json" OR dataType: "jsonp" in ajax call.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, I need to use json_encode before return or at place of return? and where do I need to use datatype?
it does not work...the console logs 'an empty string'...it seems that jquery starts before php validation...is it possible?
Then there may be like 1 is not set , according to your if else conditions , Use console.log(html); to see what u get in return. If u r gettting 0 By php it will show u same , if php sends 1 to you ,ajax will show u 1 .
console.log(html) prints me a null...if I use jsonp instead of json in dataType, ajax goes in error and not in success

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.