简体   繁体   中英

unable to pass ajax post in java script method

i came across with a minor conflict while i am reading the html image value and passing value data in java script method works fine, and in ajax POST to pass the value towards controller, and unforunelty ajax point the controller over break point but the string Country parameter is null (passing a null value =), may i know the reason why please ! Thank you !

public ActionResult Prayer_Schedule(string Country){

}


<img src="~/images/flags/india.jpg" value="india" onclick="choose(this);">

<script type="text/javascript">

    function choose(element) {
        var Country = element.getAttribute("value"); 
        $.ajax({
            type: 'POST',
            url: '../Home/Prayer_Schedule',
            data: {
                Country: Country,
            },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            cache: false,
            timeout: 100000,
            success: function (response) {
                alert('ajax success: ' + response);
                //location.href = "/thankyou.html";
            }
        });

You have to use jQuery.param for post

 data: jQuery.param({ Country: Country}),

Or use $.post

$.post('../Home/Prayer_Schedule', { Country: Country }, 

You have set contentType: 'application/json; charset=utf-8' contentType: 'application/json; charset=utf-8' so you need to send json object or you can simply remove this to get value in controller.

$.ajax({
        type: 'POST',
        url: '../Home/Prayer_Schedule',
        data: {
            Country: Country,
        },
        dataType: 'json',
        async: false,
        cache: false,
        timeout: 100000,
        success: function (response) {
            alert('ajax success: ' + response);
            //location.href = "/thankyou.html";
        }
    });

Also if you have not decorated your method with HttpPost you will need this too.

[HttpPost]
public ActionResult Prayer_Schedule(string Country){

}

It may be your javascript on the getAttribute() function. You are using value, which isn't a valid attribute for an img tag. Try this instead, using data-* attributes:

<img src="~/images/flags/india.jpg" data-value="india" onclick="choose(this);">

then in your javascript:

element.getAttribute("data-value");

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