简体   繁体   中英

How to UPDATE 1 dropdown and 4 text filed values dynamically using ajax and jquery

I have two drop down lists and 4 text fields. Now I want to change the value of the text field and the second dropdown based upon the first dropdowns value.

I succeed to change the value of only single portion of my website(either 2nd dropdown or text field) at a time dyanmically. I am not getting how to update all five (1+4) dynamically and simultaneously 在此处输入图片说明 这是PHP的一部分 在此处输入图片说明

Need more information, what you actually tried or not, what's working, what you get from your ajax, ... to help... But, basically, and based on the way you seem to do it (or, the way you want it to be done) your js (jquery) should look like this :

$(document).on('change','#yourWardSelectId',function(event){
    var currentValue = $(this).val();
    $.ajax({
        method : 'POST', //or get, or whatever
        url : 'whatever', //your url
        data : {'myValue':currentValue}, //the data you post
        dataType : 'json',
        success : function(dataReturned){
            //here is what you do on success
            $('#corporatorFieldId').val(dataReturned.corporator);
            $('#zoneNameFieldId').val(dataReturned.zoneName);
            $('#whateverId').val(dataReturned.whateverValue);
        },
        error : function(dataReturned){
            //handle your error
        }
    });
});

This is in the case where you get all your data from one ajax request... Do not use "html" but use ".val" on your items to set inner value.

Here is a "over-simplified" php example of "whatever.php", considering you use PDO :

<?php
    //returns a pdo instance
    $db = connect();
    $whatIWant = $_POST['myValue'];
    //prepare statement
    $query = $db->prepare("SELECT name,town,age FROM people WHERE searchField = :val");
    $query->execute([':val'=>$whatIWant]);
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($result);
?>

This piece of php will return a json ARRAY that looks like this :

name    |    town    |    age

myName  |    myTown  |    30

So, in your JS part, get the values like this :

var name = dataReturned.name;
var town = dataReturned.town;
var age = dataReturned.age;

2 examples of what you can do if you want to "inspect" your returned data :

console.log(JSON.stringify(dataReturned));
console.log(dataReturned.responseText);

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