简体   繁体   English

未填写必填字段,执行php

[英]Not filled the required fields, php is executed

I have html form with input fields. 我有输入字段的html表单。 Data from the form will be sent throght the ajax function in php and php returns the result in html. 来自表单的数据将通过php中的ajax函数发送,php将结果返回到html中。 Although not all fields are filled php executes and returns the result. 虽然不是所有字段都填充php执行并返回结果。 If all fields are filled not get a result from php. 如果所有字段都填满,则不会从php获得结果。

Can anyone help me to solve the problem? 任何人都可以帮我解决问题吗?

Thanks in advance 提前致谢

HTML HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<div id="inputform">
    <form>  
        Name:<br>
        <input type="text" id="firstname" required><br>
        Surname:<br>
        <input type="text" id="lastname" required ><br>
        <input type="submit" value="submit" onclick='ajax()'>
        <div id="ajaxDiv"></div>
    </form>
</div>

javascript JavaScript的

function ajax() {
var ajaxRequest;  // The variable that makes Ajax possible!

try {
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e) {
    // Internet Explorer Browsers
    try {
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
    if (ajaxRequest.readyState == 4) {
        var answer = document.getElementById('ajaxDiv');
        answer.innerHTML = ajaxRequest.responseText;
    }
};

var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;


var queryString = "?firstname=" + firstname + "&lastname=" + lastname;
ajaxRequest.open("GET", "test.php" + queryString, true);
ajaxRequest.send(null);}   

php PHP

<?php
$firstname=$_GET['firstname'];
$lastname=$_GET['lastname'];
echo $firstname;
?>

You use ajax to send form data to server and you call method ajax() on form submit. 您使用ajax将表单数据发送到服务器,并在表单提交上调用方法ajax() So, there is no need in <form> tag, because when you click on button, you call ajax() function and form is submitting automatically. 因此, <form>标签中没有必要,因为当您单击按钮时,您调用ajax()函数并且表单自动提交。

Remove <form> and change: <input type="submit" value="submit" onclick='ajax()'> to <input type="button" value="submit" onclick='ajax()'> 删除<form>并更改: <input type="submit" value="submit" onclick='ajax()'> to <input type="button" value="submit" onclick='ajax()'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM