简体   繁体   中英

Validation Form and send data to the php file

I develop a Validation Form with Javascript All think as right

but I want when Al think are accepted send the information to the php file

How I can make that ?

The HTML code :

 <?php if(isset($_GET['submit'])){ $message = ''; $email = ''; $name =''; $message = $_GET['comment']; $email = $_GET['commentMail']; $name = $_GET['commentName']; $to = "emailme"; $subject = 'New Message'; $message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email; $header = "$email"; if(mail($to, $subject, $message, $header)){ echo '<b style="color: green">Messange Send</b>'; } else{ echo '<b style="color: red">Sommthing wrong</b>'; }} ?> <html> <head> <title>Contact</title> <meta charset="UTF-8"> </head> <body onload="randNums()"> <form> <input id="commentName" onkeyup="validateName()" name="name" type="text" placeholder="Name"><label id="commentNamePrompt"></label><br> <input id="commentMail" onkeyup="validateMail()" name="mail" type="text" placeholder="Mail"><label id="commentMailPrompt"></label><br> <input id="commentPhone" onkeyup="validatePhone()" name="phone" type="text" placeholder="Phone"><label id="commentPhonePrompt"></label><br> <textarea id="comment" onkeyup="validateComment()" name="commente" placeholder="Message here"></textarea><label id="commentPrompt"></label><br> <span id="digit1"></span> + <span id="digit2"></span> = <input id="captcha" size="2" onkeyup="validateCaptcha()"><label id="captchaPrompt"></label><br> </form> <button href="index.php" name="submit" onclick="validateCommentForm()" > Send</button><label id="commentFormPrompt"> </label> <script type="text/javascript" src="javascript.js"></script> </body> </html> 

js code

 function randNums(){ var rand = Math.floor(Math.random() * 10) + 1; var rand2 = Math.floor(Math.random() * 10) + 1; document.getElementById("digit1").innerHTML = rand; document.getElementById("digit2").innerHTML = rand2; } function validateName(){ var name = document.getElementById("commentName").value; if (name.length == 0){ producePrompt("Name *", "commentNamePrompt", "red"); return false; } if(!name.match(/^[A-Za-z]*\\s{1}[A-Za-z]*$/)) { producePrompt("name wrong","commentNamePrompt","red"); return false; } producePrompt("accept", "commentNamePrompt", "green"); return true; } function validatePhone(){ var phone = document.getElementById("commentPhone").value; if(phone.length == 0){ producePrompt("phone *", "commentPhonePrompt", "red"); return false; } if(phone.length != 10){ producePrompt("10 numbers", "commentPhonePrompt", "red"); return false; } if(!phone.match(/^[0-9]{10}$/)) { producePrompt("phone wrong","commentPhonePrompt","red"); return false; } producePrompt("Accept", "commentPhonePrompt", "green"); return true; } function validateMail() { var mail = document.getElementById("commentMail").value; if(mail.length == 0){ producePrompt("mail *", "commentMailPrompt", "red"); return false; } if(!mail.match(/^[A-Za-z._\\-0-9]*[@][A-Za-z]*[\\.][az]{2,4}$/)) { producePrompt("Wrong mail","commentMailPrompt","red"); return false; } producePrompt("accept", "commentMailPrompt", "green"); return true; } function validateComment(){ var comment = document.getElementById("comment").value; var required = 30; var left = required-comment.length; if (left > 0){ producePrompt(left + " lettre" ,"commentPrompt","red" ); return false; } producePrompt("accept", "commentPrompt", "green"); return true; } function validateCaptcha(){ var captcha = document.getElementById("captcha").value; var digit1 = parseInt(document.getElementById("digit1").innerHTML); var digit2 = parseInt(document.getElementById("digit2").innerHTML); var sum = digit1 + digit2; if(captcha.length == 0){ producePrompt("captcha *", "captchaPrompt", "red"); return false; } if(!captcha.match(/^[0-9]{1,2}$/) || !captcha.match(sum)){ producePrompt("Captchas wrong","captchaPrompt","red"); return false; } producePrompt("Accept", "captchaPrompt", "green"); return true; } function submitForm(){ var server = 'http://localhost/test'; // Your PHP file var commentName = $('#commentName').val(); // The values of your form var commentMail = $('#commentMail').val(); // The values of your form var commentPhone = $('#commentPhone').val(); // The values of your form var comment = $('#comment').val(); // The values of your form $.ajax({ // Here the magic starts url: server+"/index.php", // Where this function will send the values type:"get", // To get the status of your php file data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail. if(data == 'Messange Send'){ // } else{ // } } }); } function validateCommentForm(){ if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){ jsShow("commentFormPrompt"); producePrompt("Invalide form","commentFormPrompt","red"); setTimeout(function(){jsHide("commentFormPrompt")}, 2000); } else submitForm(); } function jsShow(id){ document.getElementById(id).style.display = "block"; } function jsHide(id){ document.getElementById(id).style.display = "none"; } function producePrompt(message, promptLocation, color){ document.getElementById(promptLocation).innerHTML = message; document.getElementById(promptLocation).style.color = color; } 

that's is my code, the php code with HTML, And javascript with Ajax but when I click into submit button nothing happens, Any solution ?

function validateCommentForm(){
    if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
        jsShow("commentFormPrompt");
        producePrompt("Invalide Form ","commentFormPrompt","red");
        setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
    }
    else 
        submitForm();
}


function submitForm(){

    var server = 'url'; // Your PHP file
    var commentName = $('#commentName').val(); // The values of your form
    var commentMail = $('#commentMail').val(); // The values of your form
    var commentPhone = $('#commentPhone').val(); // The values of your form
    var comment = $('#comment').val(); // The values of your form

    $.ajax({ // Here the magic starts
        url: server+"/api.php", // Where this function will send the values
        type:"get", // To get the status of your php file
        data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
        success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
            if(data == 'Messange Send'){    
                // sucess code
            }
            else{
                // fail code
            }
        }
    });
}

Edit: You need to echo in your php echo a number 1 if sucess or a number 2 if fail.

PHP

$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];

$to = "$email";

$subject = 'New Message';

$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;

$header = "$email";

if(mail($to, $subject, $message, $header)){
  echo '<b style="color: green">Messange Send</b>';
}
else{
  echo '<b style="color: red">Sommthing wrong</b>';
}

So AJAX is about creating more versatile and interactive web applications by enabling web pages to make asynchronous calls to the server transparently while the user is working. AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.

The technologies AJAX is made of are already implemented in all modern web browsers, such as Mozilla Firefox, Internet Explorer, or Opera, so the client doesn't need to install any extra modules to run an AJAX website. AJAX is made of the following:

  • JavaScript is the essential ingredient of AJAX, allowing you to build the client-side functionality. In your JavaScript functions you'll make heavy use of the Document Object Model (DOM) to manipulate parts of the HTML page.
  • The XMLHttpRequest object enables JavaScript to access the server asynchronously, so that the user can continue working, while functionality is performed in the background. Accessing the server simply means making a simple HTTP request for a file or script located on the server. HTTP requests are easy to make and don't cause any firewall-related problems.
  • A server-side technology is required to handle the requests that come from the JavaScript client. In this book we'll use PHP to perform the server-side part of the job.

For the client-server communication the parts need a way to pass data and understand that data. Passing the data is the simple part. The client script accessing the server (using the XMLHttpRequest object) can send name-value pairs using GET or POST. It's very simple to read these values with any server script. The server script simply sends back the response via HTTP, but unlike a usual website, the response will be in a format that can be simply parsed by the JavaScript code on the client.

The suggested format is XML, which has the advantage of being widely supported, and there are many libraries that make it easy to manipulate XML documents. But you can choose another format if you want (you can even send plain text), a popular alternative to XML being JavaScript Object Notation (JSON).

Simple example with old school style:

The HTML

<html>
  <head>
    <title>AJAX with PHP: Quickstart</title>
  </head>
  <body onload='process()'>
    Server wants to know your name:
    <input type="text" id="myName" />
    <div id="divMessage"></div>
  </body>
</html>

The Magician

// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() {
    // will store the reference to the XMLHttpRequest object
    var xmlHttp;
    // if running Internet Explorer
    if (window.ActiveXObject) {
        try {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
            xmlHttp = false;
        }
    }
// if running Mozilla or other browsers
    else {
        try {
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            xmlHttp = false;
        }
    }
// return the created object or display an error message
    if (!xmlHttp)
        alert("Error creating the XMLHttpRequest object.");
    else
        return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process() {
// proceed only if the xmlHttp object isn't busy
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// retrieve the name typed by the user on the form
        name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
        xmlHttp.open("GET", "**yourPHPfiletoretrievedata**.php?name=" + name, true);
// define the method to handle server responses
        xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
        xmlHttp.send(null);
    }
    else
// if the connection is busy, try again after one second
        setTimeout('process()', 1000);
}
// executed automatically when a message is received from the server
function handleServerResponse() {
// move forward only if the transaction has completed
    if (xmlHttp.readyState == 4) {
// status of 200 indicates the transaction completed successfully
        if (xmlHttp.status == 200) {
// extract the XML retrieved from the server
            xmlResponse        = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
            xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
            helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
            document.getElementById("divMessage").innerHTML =
                '<i>' + helloMessage + '</i>';
// restart sequence
            setTimeout('process()', 1000);
        }
// a HTTP status different than 200 signals an error
        else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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