What is an example of an ajax function that can grab data based off a state change?

38 Views Asked by At

I am trying to write an ajax function that gets a post endpoint from the controller and print out data(text) based off the state the user picks on the page.

$( "#state" ).on( "change", function() {
        var stateID = $( "#state" ).val();
        var url = "/s/QD-CIT/Registration-Consent";
        event.preventDefault();
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data: stateID,
            success: function (data) {
               alert(1);//Get cosent text from response  
            },
            error: function (err) {
                alert(2);
            }
        });

I am not sure what is the conditional and how to print out the text based off the state change

I want the data to be received from the post endpoint of the controller and print out the data based off which state the user selects.

1

There are 1 best solutions below

0
Ahsan Khalid On
$( "#state" ).on( "change", function() {
    var stateID = $( "#state" ).val();
    var url = "/s/QD-CIT/Registration-Consent";
    
    // Create a data object to send to the server
    var requestData = {
        stateID: stateID 
    };

    $.ajax({
        url: url,
        type: 'POST', 
        dataType: 'json',
        data: requestData, // Send the data as an object
        success: function (data) {
       
            var consentText = data.consentText;
           
            alert(consentText);
        },
        error: function (err) {
            alert("Error: " + err.responseText);
        }
    });
});

I created an object called requestData that holds the stateID parameter, which we want to send to the server. I changed the request type to 'POST' (in uppercase) to tell the server that we're sending some data to it. Inside the success function, assume that the server will send us a special kind of message called JSON, and in that message, there will be something called consentText. then show this consentText in a pop-up box (like an alert) to the user. You can change this part to update your webpage with the consent text instead of showing a pop-up. Finally, make sure that the server we're talking to at /s/QD-CIT/Registration-Consent knows how to handle our POST request and send back the right kind of JSON message with the consentText inside it.