Call $.ajax malfunctioning - javascript

I am making a ajax call, but server side code is not hit. Instead control goes to javascript file included in project. Here is my code:
<script type="text/javascript">
function AddEmployee()
{
debugger;
// jQuery.support.cors = true;
$.support.cors = true;
var Product = new Object();
Product.ID = 10;
Product.Name = "kRISH";
Product.Price = "23";
Product.Category = "AS";
// console.log(JSON.stringify({ Name: "kRISH", Price: "23", Category: "AS" }));
var json_text = JSON.stringify(Product,null,2);
**$.ajax**
({
url: 'http://localhost:62310/api/products',
type: 'POST',
data: json_text,
contentType: "application/json;charset=utf-8",
success: function (data) { WriteResponse(data); },
error: function (x, y, z)
{
$('#contentProgress').popup("close");
alert(x.responseText + " " + x.status);
}
});
}
</script>

Is the url correct, why are we not using the relative url here. Can you please try this
$.ajax('http://localhost:62310/api/products', {
type: "post",
data: json_text,
dataType: "json",
cache: false,
contentType: "application/json",
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});

Related

How to avoid repeating the same $.ajax() call

I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

Submission issue internal server error

I am trying to submit data through form as below which gives error:
echo 'The # here does not begin a comment.'
echo The \# here does not begin a comment.
But it wont give error, if we submit like below:
echo The # here does not begin a comment.
echo The # here does not begin a comment.
That is ,without single quotes and slash ,i am unable to submit data.
Code as below:
function AjaxCallOnClick(userName, email, commentText, blogID, commentHtml, onCommentEmailID) {
var parameters = "{'commentUserName':'" + userName + "','email':'" + email + "','commentText':'" + commentText + "','blogID':'" + blogID + "','commentHtml':'" + commentHtml + "','onCommentEmailID':'" + onCommentEmailID + "'}";
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/BlogService.asmx/GetShareStoryData")%>",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Your Comment was Saved");
var getCommentList = response.d;
var allComments = '';
$('#dvMainAndReplyCommentSection').html('');
$.each(getCommentList, function (index, comments) {
var comment = comments.HtmlComment;
allComments += comment;
});
if (allComments) {
$('#dvMainAndReplyCommentSection').html(allComments);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
failure: function (response) {
alert(response.responseText);
}
});
}
What is the work around for this?
I tried like this format var parameters = JSON.stringify({ commentUserName: userName, email: email, commentText: commentText, blogID: blogID, commentHtml: commentHtml, onCommentEmailID: onCommentEmailID }); and it's working fine for me.
Try it...Removes double quotes when saving object.
function AjaxCallOnClick(userName, email, commentText, blogID, commentHtml, onCommentEmailID) {
var parameters = JSON.stringify({'commentUserName': userName,'email': email,'commentText': commentText,'blogID': blogID,'commentHtml': commentHtml,'onCommentEmailID': onCommentEmailID});
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/BlogService.asmx/GetShareStoryData")%>",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Your Comment was Saved");
var res=JSON.parse(response);
var getCommentList = res.d;
var allComments = '';
$('#dvMainAndReplyCommentSection').html('');
$.each(getCommentList, function (index, comments) {
var comment = comments.HtmlComment;
allComments += comment;
});
if (allComments) {
$('#dvMainAndReplyCommentSection').html(allComments);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
failure: function (response) {
var res=JSON.parse(response);
alert(res.responseText);
}
});
}

ASP.NET WebMethod returns whole page to JQuery ajax requests

I am building a web application where I am calling a ASP.NET WebMethod from jQuery on click of a textbox. The problem is that it returns me the whole ASPX Page. How can I get just the values returned by the Web Method? This is my code:
$("#<%= groupNameTxt.ClientID %>").click(function () {
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: "{ }",
// dataType: "json"
type: "POST",
// contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
});
This is my WebMethod from CodeBehind
[System.Web.Services.WebMethod]
public static List<Groups> GetGroupList(string mail)
{
List<Groups> empList = new List<Groups>();
empList.Add(new Groups() { GroupID = 1, GroupName = "Admins" });
empList.Add(new Groups() { GroupID = 2, GroupName = "Employees" });
empList.Add(new Groups() { GroupID = 3, GroupName = "Engineers" });
empList.Add(new Groups() { GroupID = 4, GroupName = "Managers" });
empList.Add(new Groups() { GroupID = 5, GroupName = "Assistants" });
return empList;
}
You need to pass email as parameter as webmethod is expecting a parameter.
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: JSON.stringify({ email: "someemail#test.com"}),
dataType: "json"
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
Also specify contentType and dataType
The page was returning since it was not hitting the Web Method. The below code will hit the Web Method correctly. Pass in data as shown below.
$.ajax({
url: "UserGroups.aspx/GetGroupList",
data: '{ mail: "a#a.com"}',
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});

jquery Ajax call - data parameters are not being passed to MVC Controller action

I'm passing two string parameters from a jQuery ajax call to an MVC controller method, expecting a json response back. I can see that the parameters are populated on the client side but the matching parameters on the server side are null.
Here is the javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List/AddItem",
data: "{ ListID: '1', ItemName: 'test' }",
dataType: "json",
success: function(response) { alert("item added"); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
Here is the controller method:
Function AddItem(ByVal ListID As String, ByVal ItemName As String) As JsonResult
'code removed for brevity
'ListID is nothing and ItemName is nothing upon arrival.
return nothing
End Function
What am I doing wrong?
I tried:
<input id="btnTest" type="button" value="button" />
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
and C#:
[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
return Content(ListID + " " + ItemName);
}
It worked. Remove contentType and set data without double quotes.
If you have trouble with caching ajax you can turn it off:
$.ajaxSetup({cache: false});
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
var json = {"ListID" : "1", "ItemName":"test"};
$.ajax({
url: url,
type: 'POST',
data: username,
cache:false,
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success:function(response){
console.log("Success")
},
error : function(xhr, status, error) {
console.log("error")
}
);
In my case, if I remove the the contentType, I get the Internal Server Error.
This is what I got working after multiple attempts:
var request = $.ajax({
type: 'POST',
url: '/ControllerName/ActionName' ,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ projId: 1, userId:1 }), //hard-coded value used for simplicity
dataType: 'json'
});
request.done(function(msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
alert("Request failed: " + jqXHR.responseStart +"-" + textStatus + "-" + errorThrown);
});
And this is the controller code:
public JsonResult ActionName(int projId, int userId)
{
var obj = new ClassName();
var result = obj.MethodName(projId, userId); // variable used for readability
return Json(result, JsonRequestBehavior.AllowGet);
}
Please note, the case of ASP.NET is little different, we have to apply JSON.stringify() to the data as mentioned in the update of this answer.

Categories