Example of Using ajax to submit POST data and ajax to submit post Data

Source: Internet
Author: User
Tags php server

Example of Using ajax to submit POST data and ajax to submit post Data
Problem description


We asynchronously submit the data in the input and checkbox of a form to the php server. After processing, the data is returned.


Position displayed after submission:



Difficulties


Use the onsubmit attribute of the from form to block form submission.
<form action="http://www.baidu.com" onsubmit="return check()">

Use the return false function of the check function to prevent form submission, so that the data is not refreshed and submitted.
Obtain the value of the option selected by the check box.
Checkbox label section:
<Input type = "checkbox" name = "checkbox" id = "multi-choiceA" value = "A"> Option A <br/> <input type = "checkbox" name = "checkbox" id = "multi-choiceB" value = "B"> Option B <br/> <input type = "checkbox" name = "checkbox" id = "multi-choiceC "value =" C "> Option C <br/> <input type =" checkbox "name =" checkbox "id =" multi-choiceD "value =" D "> Option D <br/>


Javascript processing:
Var str = document. getElementsByName ("checkbox"); var answer = ""; for (var I = 0; I <str. length; I ++) {if (str [I]. checked = true) {answer + = str [I]. value ;}} if (answer = "") alert ('Check the answer and submit'); else {// The user selects the relevant answer to process var xmlhttp;

Use ajax technology to interact with the background
var xmlhttp;xmlhttp = new XMLHttpRequest();xmlhttp.open("POST","function.php",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("qid="+qid+"&answer="+answer);xmlhttp.onreadystatechange=function()  {  if (xmlhttp.readyState==4 && xmlhttp.status==200)    {    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;    }  };

Region Code frontend index.html
<! Doctype html> 

Backend function. php
<! Doctype html> 

Effect display:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.