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>
You need to wire up the click event when the DOM has been loaded.
$(document).ready(function(e) {
$('#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);
}
});
});
});
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 !
Related
I have this simple ajax method:
$.ajax({
type: 'POST',
url: 'http://localhost:1195/widget/postdata',
datatype: "jsondata",
async: false,
success: function (data) {
alert("ok")
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
And this simple method in c#:
[HttpPost]
public JsonResult PostData()
{
return Json("1");
}
When I check the inspector console I have "1" in response but my ajax method always goes to error function.
Why is it so?
In your AJAX call it should be dataType: "json" and not datatype: "jsondata". You can refer to the docs
Also use #Url.Action tag in your url call: url: '#Url.Action("postdata", "widget")'
For a small test, I have used the following AJAX call to the same controller method that you have posted and I am getting the correct result:
$(document).ready(function () {
$("#button_1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url:'#Url.Action("PostData", "Home", null, Request.Url.Scheme)',
datatype: "json",
async: false,
success: function (result) {
alert(result);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
<button id="button_1" value="val_1" name="but1">Check response</button>
Output:
Change the Ajax request to the following :
$.ajax({
type: 'POST',
url: '/widget/postdata',
datatype: "json",
async: false,
success: function (data) {
console.log(data);// to test the response
},
error: function (data) {
alert(data.status + ' ' + data.statusText);
}
});
Always use relative URL instead of full URL that contains the domain name, this will make the deployment easier so you don't have to change the URls when going live
I want a C# code behind to be run every second. After googling, I wrote these codes:
<script type="text/javascript">
var myVar = setInterval(function () { start() }, 1000);
function start() {
time2 = 5;
//alert("Hello");
$.ajax({
type: "POST",
url: "WebForm1.aspx/refresh",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Hello");
},
failure: function () {
alert("Error");
}
});
}
</script>
And the code behind is:
[System.Web.Services.WebMethod]
public static void refresh()
{
//some code
}
But nothing happens. What's wrong?
UPDATE: I installed Firebug and observed that it is reporting "500 Internal Server Error". What does it mean ?
Everything looks good. But i assume you are not calling the JavaScript function.
<script type="text/javascript">
var myVar = setInterval(function () { start() }, 1000);
function start() {
alert('hi');
time2 = 5;
//alert("Hello");
$.ajax({
type: "POST",
url: "default.aspx/refresh",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Hello");
},
failure: function () {
alert("Error");
}
});
}
myVar; //------------------> Call the function
</script>
just call the function by calling myVar;
Please consider below code. I am loading my products view using below ajax call.
$.ajax({
cache: true,
type: "GET",
url: url,
data: json.stringify(data),
success: function (data) {
var mainview = $(data).find(".maindiv");
$('.maindiv').replaceWith(mainview);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error Occured...... No Products Found');
},
complete: function () { subscribeProgress.hide(); }
});
Now when I load this view there is add to cart button for each product on which another ajax call is executed to check if customer is registerd or guest and accordingly popup for register is shown. Now for registering customer, another ajax method is called which works properly but json data is not returned to the success and is directly shown on the page.
Below id code for registering customer through popup
$('#formpopupReg').unbind('submit');
$('#formpopupReg').bind('submit', function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
// you can post your model with this line
data: $(this).serialize(),
success: function (data) {//Json should get back to this call but doesnt
if (data.status == "Wrong email") {
$('#modelerrors').text("Wrong email");
}
if (data.status == "emailexists") {
//Code on Error
}
if (data.status == "registersuccess") {
location.reload();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Internal Error.');
},
complete: function () { }
});
}
return false;
});
Any solutions.I want json data to return back to success call.
Add dataType:"json" to your ajax call.
Try this, problem is your } is extra in your code, and missing dataType: 'json', if you use json.
$.ajax({
cache: true,
url: url,
dataType: 'json',
data: json.stringify(data),
success: function (data) {
var mainview = $(data).find(".maindiv");
$('.maindiv').replaceWith(mainview);
}
error: function (xhr, ajaxOptions, thrownError) {
alert('Error Occured...... No Products Found');
},
complete: function () { subscribeProgress.hide(); }
});
I am trying to get list of user data from a web service file which is called via AJAX. Here is my code :
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
var param;
var resultarr;
$(document).ready(function () {
param = document.getElementById('MainCT_dtvJobVac_PIC').value;
// Load countries then initialize plugin:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
//alert(result.d)
resultarr = result.d;
}
})
// Initialize autocomplete with local lookup:
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
});
</script>
resultarr will output an array with this values :
[ "Administrator", "Guest", "krbtgt", "phendy" , "Genin" , "Hendra" , "andri" ]
It throws this:
TypeError: this.source is not a function [Break On This Error]
this.source( { term: value }, this._response() );
What do I need to fix here? I am struggling on this for 2 days, some help would be appreciated.
Move the autocomplete initialization inside the ajax success callback:
success: function (result) {
//alert(result.d)
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}
Ajax calls are asynchronous. Lets examine your code:
$.ajax({ .... } ); // (1)
$('#MainCT_dtvJobVac_PIC').autocomplete({ ... } ) // (2)
The autocomplete initialization (2) occurs after calling the service (1), but it is unclear if the AJAX request has succeeded and returned the response. There is a great chance that you are initializing the autocomplete with empty or undefined data - when the connection is slow, or it fails for some reason, the success callback might not get executed at the point of setting the autocomplete (2). The correct way to do this is to initialize the autocomplete in the AJAX callback, because then the response data is guaranteed to be present:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}
})
I have a Web User Control with javascript and css blocks. I'm using jQuery to dynamically load it into the main page. How do I make the alert('haha') to execute when the user control is loaded into the div called "divTable"?
In my .ascx file, I have
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
</script>
In the .aspx file, I have
<script type="text/javascript">
$(function () {
$('button').click(GetTable);
});
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
</script>
In the .svc file, I have
[OperationContract]
public string RenderUC(string path, string id1, string id2)
{
Page pageHolder = new Page();
var viewControl = (ParameterizedTableControl)pageHolder.LoadControl(path);
viewControl.ID1= id1
viewControl.ID2 = id2;
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, true);
return output.ToString();
}
Any javascript that you want to run once the ajax operation is complete should go in the success handler.
function GetTable() {
debugger;
var id_1 = $('#txtID1').val();
var id_2 = $('#txtID2').val();
$.ajax({
url: 'Services/Data.svc/RenderUC',
data: JSON.stringify({ path: 'Controls/ParameterizedTableControl.ascx', id1: id_1, id2: id_2 }),
type: "POST",
contentType: "application/json",
dataType: "json",
success: function (data) {
debugger;
$('#divTable').html(data);
//
// insert whatever you want here
//
},
error: function showError(xhr, status, exc) {
debugger;
alert('error');
}
});
}
You can call your function inside your <script> block in the ascx control like this:
<script type="text/javascript">
function pageLoad(sender, args) {
alert('haha');
}
pageLoad();
</script>
This will make your script run when the browser renders your script tag.