javascript - 如何在一份表单提交上执行 2 个 AJAX 请求?

标签 javascript jquery sql ajax salesforce

简短版本:

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

  • 我有代码可以将表单数据作为潜在客户发送给 Salesforce

这两个单独工作都很好(如果我将表单“action”更改为任一 PHP 脚本)——但是当我尝试将它们组合成 1 个 PHP 脚本时,表单无效,我不明白为什么.

这是插入数据库的代码:

<?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 文件中一起工作。

这是表单和 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>

最佳答案

组合脚本时是否会输出两次 HTTP header ?

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

关于javascript - 如何在一份表单提交上执行 2 个 AJAX 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19122665/

相关文章:

javascript - 所有匹配元素的 jQuery .html()

javascript - 使所有 JavaScript 在 ajax 内容上正常工作

javascript - 使用 RegEx 和 .replace 替换用户输入的文本?

javascript - CSS 面板问题

sql - 将文本转换为 xml 错误非法限定名称字符

sql - like 查询中的逗号无法返回任何结果

mysql - 表引用的顺序在 MySQL 中重要吗?

javascript - Wordpress admin-ajax.php 在没有处理函数的情况下快死了 "0"

javascript - 尝试在 ember.js 中 self 引用模型时出错

javascript - Skrollr 淡出文本