Javascript将表单发送到PHP

时间:2015-02-06 20:44:06

标签: javascript php html mysql

我正在尝试让我的HTML表单通过Javascript,然后将其传递给将发送给MySQL的PHP​​。

但是我要么在浏览器中加载JS文件,要么在浏览器中加载PHP文件。

这是我的HTML表单:

<div class="form" id="form" onclick="submitForm()">
<form id='contactform' action="js/contactform.js" method="post" onSubmit="submitForm()">
<input type="text" id="name" placeholder="Name" autofocus required><br>
<input type="text" id="email" placeholder="Email" required><br>
<input type="tel" id="telephone" placeholder="Telephone"><br>
Enquiry : <input type="radio" id="subject" value="enquiry" required>
Booking : <input type="radio" id="subject" value="booking" required><br>
<textarea id="message" required rows="20" cols="20" placeholder="Enter your message and I will try to get back to you within 2 days."></textarea><br>

<input type="submit" name="submit" value="Submit" class="submitbutton"/>
<input type="reset" name="clearbutton" value="Clear" class="clearbutton"/>
</form>
<div id="outcome"></div>

我希望将表单提交的结果放入&#34;结果&#34;格

我的JS代码:

function getOutput() {
  getRequest(
      'php/getinfo.php', 
       drawOutput,
       drawError
  );
  return false;
}



// handles drawing an error message
function drawError () {
    var container = document.getElementById("content");
    container.innerHTML = 'Bummer: there was an error!';
}

// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById("content");
    container.innerHTML = responseText;
}


// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req .readyState == 4){
            return req.status === 200 ? 
                success(req.responseText) : error(req.status)
            ;
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}
        function submitForm(){
            var name = document.getElementById('name').value;
            var booking = document.getElementById('subject').value;
            var enquiry = document.getElementById('subject').value;
            var email = document.getElementById('email').value;
            var telephone = document.getElementById('telephone').value;
            var message = document.getElementById('message').value;
            getRequest(
                'php/form.php?' + params, //URL for the PHP file
                procesOutput,
                processError
            );
            return false;
        }

        function processOutput(){
            var  container = document.getElementById('outcome');
            container.innerHTML = responseText; 
        }

        function processError(){
            alert("There has been an error, please try again"); 
        }

和我的PHP代码:     

    $con=mysqli_connect("DBLocation","Username","Password",'DBName');

    if (mysqli_connect_errno()){
        die("Error: "  . mysqli_connect_error());
    }

    $result = mysqli_query($con,"INSERT INTO `Contact`(`Name`, `Email`, `Telephone`, `Enquiry`, `Booking`, `Message`) VALUES ([value-2],[value-3],[value-4],[value-5],[value-6],[value-7])");

    if ($conn->query($sql) === TRUE){
        echo "Thank you for contacting us, I will replay to you soon!"; 
    } 

    else {
        echo "I'm sorry but an Error has occured. Please try again shortly";
    }

    mysql_close($conn);
?>

我已经看过w3schools页面以及其他一些问题,但我似乎无法理解它。

3 个答案:

答案 0 :(得分:1)

有几件事,首先是getRequest是什么?第二关,responseText定义在哪里?第三,我会检查你的控制台,因为我很确定submitForm中有错误。我看到很多getElementById s,但你的输入都没有与它们相关的ID:

<input type="text" name="name" placeholder="Name" autofocus required>

应该是:

<input type="text" id="name" placeholder="Name" autofocus required>

答案 1 :(得分:0)

  

这是demo in JSFiddle

  1. 删除onClickonSubmitaction="js/contactform.js" method="post"属性,因为您不需要它们。在js中捕获表单提交。 How to? - link

  2. 在表单元素上添加ID,以便您可以选择它们:

  3. var name = document.getElementById('name').value;

    1. 使用jQuery($.post)发出How to? - Link请求并处理成功和失败回调。 (我不明白您为什么要发帖请求,我会向您推荐$.get请求。

答案 2 :(得分:0)

我相信你想使用Ajax,你可以轻松地使用jQuery。

我相信您的问题的答案就在这个页面上:https://learn.jquery.com/ajax/ajax-and-forms/

如果jQuery对你而言是新的,你可能想要阅读一些关于jQuery的内容:https://learn.jquery.com/about-jquery/

如果您不想使用jQuery,可以直接在javascript中使用XMLHttpRequest。