Akhilesh Akhilesh - 5 months ago 9
Ajax Question

JQuery button is not triggering service call via ajax

I have a JSON service and i am trying to execute this service via ajax call through jquery in webpage. When i have created button and trying to execute click event but i am not able to get any alert message as well as service call also not triggering that means click event itself is not firing at all . please help!

below is code

<title></title>
<script src="JavaScript.js"></script>
<script type="text/javascript">
$(document).ready(function () { });
$('#buttonnew').click(function () {
alert("Hi");
$.ajax({
url: 'service2.svc/GetRestriction',
method: 'post',
contentType: 'application/json',
data: ({ property: '99883', code: 1 }),
dataType: 'json',
success: function (DATA) {
alert("hi");
},
error: function (err) {
alert(err);
}
});
});
</script>

Answer

I think the only error you have in your code is that you are asigning tht click event on the button before document is ready. So you can just Try this :

 <title></title>
    <script src="JavaScript.js"></script>
    <script type="text/javascript">
        $(document).ready(function () { 
           $('#buttonnew').click(function () {
            alert("Hi");
            $.ajax({
                url: 'service2.svc/GetRestriction',
                method: 'post',
                contentType: 'application/json',
                data: ({ property: '99883', code: 1 }),
                dataType: 'json',
                success: function (DATA) {
                    alert("hi");
                },
                error: function (err) {
                    alert(err);
                }
            });
          });
        });
    </script>

I've tested it with Jquery 2.2.2.

I hope it helps !

Comments