-3

I am working on a Single Page Application in MVC4. I have a dropdown box. When I select that drop down box, the onchange event will fire calling some JavaScript.

I need the JavaScript to call the controller and have the controller return a JSON result of some data (I know how to get the data). Could anyone help me get a basic framework laid out for this?

2 Answers 2

1

Wire up the onchange javascript event to your select element

In the event function for the onchange, have ajax send the value from the select element to a controller.

In the controller/action method do your work based on the value and then prepare json data (perhaps serialize?) and then return it.

In the success part of the ajax call, parse or otherwise use the returned json data.

Sign up to request clarification or add additional context in comments.

Comments

0

in your controller constructor:

define('_IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');

Before you load your view check the _IS_AJAX variable:

if(_IS_AJAX) {
    //echo json_encode(data you want to return);
} else {
    // load view normally
}

in your view (using jQuery)

$('#dropdownid').change(function() {
    $.ajax({
        url: requesturl,  //your controller URL
        dataType: 'json',
        success: function(response) {
            //Do stuff with data
            }
        },
        error: function(request, error, errormessage) {
            $("#error").html(error + '\n' + errormessage);
        }
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.