如何在一个表单上执行2个AJAX请求?

时间:2013-10-01 17:47:55

标签: javascript jquery sql ajax salesforce

简短版本:

  • 我有代码将表单内容插入数据库

  • 我有代码将表单数据作为主要内容发送给Salesforce

这两个工作都很好ALONE(如果我将表单“action”更改为任一PHP脚本) - 但是当我尝试将它们组合成1个PHP脚本时,表单无效,我无法弄清楚为什么

以下是插入DB的代码:

<?php
include ".db_config.php";

/* open a connection to the database */
$link = connect_db();

/* grab all of the required fields */
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$pcode = $_POST['pcode'];
$terms = $_POST['terms'];
$news = $_POST['news'];
$facebookConnection = '0';

/* check to make sure it's valid email address */
$email = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$language = $_POST['language'];

/* check to see if this was a facebook connection */
$facebookID = '';
if(isset($_POST['facebookID'])){
    $facebookID = $_POST['facebookID'];
}

/* check to see if this signature connected to Facebook */
if($facebookID != ""){
    $facebookConnection = '1';
}

/* set the true/false flag for the terms and conditions agreement. */
if ($terms == 'terms'){
    $terms = 1;
}
else{
    $terms = 0;
}

/* set the true/false flag for the updates sign up */
if($news =='news'){
    $news = 1;
}
else {
    $news =0;
}

$success='';
$error='';

// Check to see if the email exists already in the database
$query = "select count(*) as counting from signedUsers where eMailAddress ='$email'";
$result = do_query($query);

$emailIncluded = '0';
/* get the number of rows from the table where this email address is. */
while($row = mysql_fetch_array($result))
{
    /* if there is 1 or more row, then the email exists. */
    if ($row["counting"] > 0)
    {
        $emailIncluded = '1';
    }
}

/* if the email address doesn't exist, save it and return 'success' */
if ($emailIncluded == '0'){
    $insert = "insert into signedUsers (FirstName, LastName, eMailAddress, PostalCode, ToC,eMailUpdates, language, facebookID, FacebookConnection) values('$firstName','$lastName','$email', '$pcode', $terms, $news, '$language', '$facebookID', $facebookConnection)";// Do Your Insert Query
    if(mysql_query($insert)) {
        $success='1';
    } else {
        $error='failed insert';
    }
}
/* if the email address exists, return 'error' to be dealt with on the front end that explains it. */
else {
    $error = 'email exists';
    $success = '';
}

$arr = array(
  'success'=>$success,
  'error'=>$error
);

if ($success == '1')
{
    header('Content-Type: application/json');
    $arr = array(
        'success'=>$success,
    );
    echo json_encode($arr);
}
else
{
    header('HTTP/1.1 500 Internal Server');
    header('Content-Type: application/json');
    //die('ERROR');
    //  or:

    die(json_encode(array('message' => 'ERROR', code => $error)));
}

mysql_close($link);
?>

以下是发送给sailesforce的代码:

<?php
$req  = "&lead_source=" . urlencode($_GET["1"]);
$req .= "&first_name=" . urlencode($_GET["2"]);
$req .= "&last_name=" . urlencode($_GET["3"]);
$req .= "&zip=" . urlencode($_GET["4"]);
$req .= "&email=" . urlencode($_GET["5"]);
$req .= "&debug=" . urlencode("0");
$req .= "&oid=" . urlencode("00Di0000000fnSP"); 
$req .= "&retURL=" . urlencode("#");
$req .= "&debugEmail=" . urlencode("sam.stiles@orangesprocket.com");

$header  = "POST /servlet/servlet.WebToLead?encoding=UTF-8 HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.salesforce.com\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.salesforce.com', 80, $errno, $errstr, 30);
if (!$fp) {
echo "No connection made";
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
echo $res;
}
}
fclose($fp);
?>

同样,这些都是单独工作,机器人不在同一个PHP文件中。

这是表格&amp; AJAX:

//Setup contact form validation                         
                                jQuery('#petition-form').validate({
                                    rules: {
                                        firstName: "defaultInvalid",
                                        lastName: "defaultInvalid",
                                        email: "defaultInvalid",
                                        email: "emailValid",
                                        emailConfirm: "defaultInvalid",
                                        emailConfirm: "emailValid",
                                        pcode: "postalcode"
                                    },
                                    messages: {
                                        firstName: "",
                                        lastName: "",
                                        email: "",
                                        emailConfirm: "",
                                        pcode: "",
                                        terms: ""
                                    },
                                    errorLabelContainer: '#message',
                                    onkeyup: false,
                                    onfocusout: false,
                                    onclick: false,
                                    submitHandler: function(form){  
                                        //Serialize the form data
                                     //Serialize the form data
                                        var formData = jQuery('#petition-form').serialize();
                                        //Send the form data to the script
                                        jQuery.ajax({
                                            type: 'POST',
                                            url: '/resource/php/signThePetition.php',
                                            data: formData,
                                            dataType: 'json',
                                            error: contactFormErrorMsg,
                                            success: contactFormSuccessMsg
                                        });


                                        //Stop the form from refreshing the page on submit
                                        return false;
                                    }
                                });

                            });

                            //Contact form error messages
                            function contactFormErrorMsg() {
                                jQuery('#message').show();
                                jQuery('[name="emailConfirm"]').val('This email has already signed the petition. Thank you.');                      
                                return false;
                                /* this means that the email address already exists */
                            }

                            //Contact form success messages
                            function contactFormSuccessMsg() {  
                                jQuery('input, select').removeClass('error').removeClass('valid');
                                jQuery('#petition-2').fadeOut();
                                jQuery('#petition-3').fadeIn();                         
                                resetForm(jQuery('#petition-form'));
                            }                   

                        // ]]>
                        </script>

                        <form name="petition-form" id="petition-form" action="/resource/php/sendEmail_contact.php" method="post">
                            <p id="message">There was an error in the form below. Please fix it before proceeding.</p>
                            <input type="text" name="firstName" placeholder="First name*" class="required short pad">
                            <input type="text" name="lastName" placeholder="Last name*" class="required short"><br />
                            <input type="text" name="email" id="email" placeholder="Email*" class="required email"><br />
                            <input type="text" name="emailConfirm" placeholder="Confirm email*" class="required email" equalTo="#email"><br />
                            <input type="text" name="pcode" placeholder="Postal code*" class="required short pad"><br />
                            <input type="checkbox" name="terms" value="terms" class="required"><span class="terms">I have read and agree to the <a href="#" title="Terms & Conditions" class="terms">terms and conditions</a></span><br />
                            <input type="checkbox" name="news" value="news" checked="checked">Send me updates and action alerts from Partners for Mental Health
                            <input type="hidden" name="language" id="language" value="en_US" class="required" ><br />
                            <input type="hidden" name="facebookID" id="facebookID" value="" class="required" >
                            <div id="form-buttons">
                                <button type="submit" value="Submit" name="submit" class="black-button">Submit</button>
                            </div>
                        </form>

1 个答案:

答案 0 :(得分:0)

组合脚本时是否输出两次HTTP标头?

顺便说一句,没有理由你不能连续两次关闭jQuery.ajax(),每个脚本一次。