简体   繁体   中英

How to call part of a form by Ajax?

I have a form with lots of boxes. I want to add a field of checkbox as the values come from a php file via Ajax call. How to handle a form within another form?

<form action="result.php" method="post">
<input ...

-------Inner form (imaginary form to perform Ajax call)
TYPE YOUR COUNTRY AND POPULATE CITY
(here user types a country and we populate cities from city.php?q=typed-country. 
City will return by the output of city.php file. In other words, output of 
city.php is exactly list of cities, which can be formatted with required 
CHECKBOX codes)
List of cities as CHECKBOX; e.g.
<input type="checkbox" name="city" value="city1" />
<input type="checkbox" name="city" value="city2" />
<input type="checkbox" name="city" value="city3" />
--------

<input type="submit" value="Submit" />
</form>

There are example of two select field for capturing cities for selected country; but here I need TYPE INPUT for country and CHECKBOX for resulting cities.

var ajax = new XMLHttpRequest();
ajax.open('GET','cities.php?q='+document.getElementById('country').value,true);
ajax.send();
citiesList = new Array();
ajax.onreadystatechange = function(){
    if(ajax.readyState == 4){
        citiesList = ajax.responseText.split(',');
    }
}
for(var i=0;i<citiesList.length;i++){
document.getElementById('citiesListContainer').innerHTML+='<input type="checkbox" value="'+citiesList[i]+'" /> '+citiesList[i]+'<br>';
}

Use the above code where your query returns a list of cities, with each city being separated by a comma. In your HTML, you have a div, with the id citiesListContainer. You could also use the appendChild method to add each individual checkbox, but mine is the lazy man's answer. Demo

You can't have a form inside of a form. You can make the entire form submit (and just use necessary data) or separate the two forms.

use .change on the country

$("#country").change(function () {    
    $("select option:selected").each(function () {        
        var value = $(this).value()
        ajax to your php, return info you need
            modify/build your city information
    });    
})

that would example would be for a select box, however the principle of using .change would be the same for any type, though you wouldn't need the select option:selected.each bit

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