Pase una variable de un archivo PHP a otro a través de $.post

I have a contact form that passes the data via jQuery $.post.

JS

$(function () {
    $("#contact_form").submit(function (a) {
        a.preventDefault();
        $.post("<?php echo home_url('/_asset/contact.php'); ?>", {
            contact_name    :   $("#contact_name").val(),
            contact_email   :   $("#contact_email").val(),
            contact_subject :   $("input:radio[name=subject]:checked").val(),
            contact_textarea:   $("#contact_textarea").val(),
            contact_postid  :   $("#contact_postid").val(),
        }, function (a) {
            $("div#response").removeClass("hidden");
            $("div#response").delay(1E3).html(a);
        });
    });
});

contacto.php

$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST["contact_textarea"];
$contact_postid = $_POST['contact_postid'];
$contact_address = $_SERVER['REMOTE_ADDR'];

if( empty($contact_name) && empty($contact_email) && empty($contact_subject) && empty($contact_message) ) {
    die('You must fill out all fields amigo!');
}

// Build that email boy!
if( !empty($contact_postid) ) { $email_id = ' (' . $contact_postid . ')'; }
$email_to        =  'email@example.com';
$email_subject   =  'Contact Form: ' . $contact_subject . $email_id;

$email_header    =  'From: ' . $contact_name . '<' . $contact_email . '>' . "\r\n";
$email_header   .=  'Reply-To:' . $contact_email . "\r\n";
$email_header   .=  'Content-type: text/html; charset=iso-8859-1' . "\r\n";

$email_message   =  nl2br($contact_message);

// Try sending the email
if(!mail($email_to, $email_subject, $email_message, $email_header)){
    $status = 'red';
    die('Error sending email.');
} else {
    $status = 'green';
    die('Email sent!');
}

Formulario PHP

<div class="respond_form">
<form method="post" id="contact_form">
    <h2>Let's get contacting!</h2>
    <div id="response" class="hidden alert <?php echo $status; ?>"></div>

    <div class="line">
        <label for="contact_name" title="Please enter your name (required)">Your name <span class="required">*</span></label>
        <input type="text" name="contact_name" id="contact_name" tabindex="1" placeholder="John Smith" required="required"/>
    </div>

    <div class="line">
        <label for="contact_email" title="Please enter your email (required)">Your email (so we can contact you) <span class="required">*</span></label>
        <input type="email" name="contact_email" id="contact_email" tabindex="2" placeholder="mail@example.com" required="required"/>
    </div>


    <?php if( isset($_GET['subject']) ) { ?>
        <input hidden="hidden" name="subject" type="radio" value="<?php echo $_GET['subject']; ?>" checked="checked">
        <?php if( isset($_GET['PostID']) ) { echo '<input hidden="hidden" id="contact_postid" name="postid" type="input" value="' . $_GET['PostID'] . '">'; } ?>
    <?php } else { ?>
        <div class="line">
            <label>What is the message in regards to? <span class="required">*</span></label>
            <ul style="list-style:none; margin: 0; padding: 0;">
                <label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Advertising"<?php if( $_GET['subject'] == 'advertising' ) { echo ' checked="checked"'; } ?>>Advertising</label>
                <label style="font-weight:normal;"><input style="margin-right: 10px;" name="subject" type="radio" value="Contribute an Article"<?php if( $_GET['subject'] == 'contribute' ) { echo ' checked="checked"'; } ?>>Contribute an Article</label>             
            </ul>
        </div>
    <?php } ?> 

    <div class="line">
        <label for="contact_textarea" title="Briefly explain your message (required)">Briefly explain your message <span class="required">*</span></label>
        <textarea name="contact_textarea" id="contact_textarea" rows="10" tabindex="3" maxlength="500" required="required"></textarea>
    </div>

    <input type="submit" id="contact_send" name="contact_send" class="button glow" value="Send Message"/>

</form>
</div>

As you can see, I've tried setting a $status en la mail() function but that didn't work. I'm not entirely sure what's going on with the whole thing (found it ages ago and just built around it) but I know the die() message emits into the div#response.

Effectively I was hoping to add a class to the div#response if the email was successful or not.

OH! and incase someone wants to comment on the lack of security, or checking of $_POST data, I've stripped it for here :]

preguntado el 05 de mayo de 13 a las 12:05

Can you provide more detail on what's going wrong than "it doesn't work"? Where do things fail? Does the code produce an error message? Are the values of your variables what you expect them to be? -

qué estás esperando $status to do? You call die() right after you set it so it is never used for anything -

Your check to see if all fields have been filled out actually just tests if there's at least one field that's been filled out. You should use || en lugar de &&. -

@ASGM sorry forgot to add the form! There aren't any "it doesn't work" I'm asking, like it says in the main question how to pass a variable from one PHP file to another. Meaning, like the second last paragraph I want to get the variable $status from contact.php to the PHP form. -

@charlietfl hoping to get the $status to echo out into the form. See the div#response in the PHP Form. -

1 Respuestas

$.post sends the data to contact.php and loads its response.

In your case, the response is text that can be "Error sending email." or "Email sent!" (from what you posted) so you just need to test the value and add the related class.

$(function () {
    $("#contact_form").submit(function (a) {
        a.preventDefault();
        $.post("<?php echo home_url('/_asset/contact.php'); ?>", {
            contact_name    :   $("#contact_name").val(),
            contact_email   :   $("#contact_email").val(),
            contact_subject :   $("input:radio[name=subject]:checked").val(),
            contact_textarea:   $("#contact_textarea").val(),
            contact_postid  :   $("#contact_postid").val(),
        }, function (a) {
            $("div#response").removeClass("hidden").addClass( (a=="Email sent!") ? "email-success" : "email-error" );
            $("div#response").delay(1E3).html(a);
        });
    });
});

contestado el 05 de mayo de 13 a las 13:05

This works only it adds both classes. Okay let me explain. I've stripped the validation checking for empty fields, and malicious <script> tags in the form. If a field is empty, it passes through as your email-error class. Then if I successfully fill out the form, it then adds email-success, only it doesn't style the div properly. Any way to addClass().removeClass() to get it to toggle? - markb

Also thank you for actually reading the question and answering it rather than other sections of the code. - markb

totally answered my own dilemma! I changed your code to: toggleClass( (a=="Email sent!") ? "email-error" : "" ); added the classes email-error email-success to the DIV and bingo! Unless there's a better way? - markb

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.