When I use jquery $ajax, I get the data as json
But when using angular http service, I get the response as xml.
This is my both code (angular and jquery ajax)
var _getList = function () {
var list = [];
var deferred = $q.defer();
$.ajax({
type: "POST",
url: '/Landing/manage/WebService.asmx/GetList',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data && data.d) {
list = data.d;
deferred.resolve(list);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
deferred.reject(xmlHttpRequest);
}
});
//angular
$http({
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": "application/json"
}
}).success(function (data) {
console.log(data);
deferred.resolve(data);
})
.error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
And this is my web method code With json format return
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat =
System.Web.Script.Services.ResponseFormat.Json)]
public tblCampaignCollection GetList()
{
tblCampaignCollection coll = Campaign.AdminGetAll();
return coll;
}
The request you are performing is not a real POST Request, I had a similar issue, if you read the console network TAB you will see that it is a GET request.
What I do if I want to perform a POST in a service is the following:
function myService(xxxParam) {
var request = $http({
method: 'POST',
headers: {"Content-Type": 'text/plain; charset=UTF-8'},
url: serviceURL,
data: {
firstPostParam: "string",
secondPostParam: 1,
thirdPostParam: xxxParam
}
});
return ( request.then(handleSuccess, handleError) );
}
try with
$http({
method: 'POST',
url: '/Landing/manage/WebService.asmx/GetList',
headers: {
"Content-Type": 'application/json; charset=UTF-8'
},
data: {
dataType: "json"
}
})...
I hope it helps.
Related
I am trying to upload file using Ajax.
The Error status is 200 ok .
Response text is my MasterPage HTML Code.
The Request never went to the Back-end as i am debugging with a breakpoint into the method.
so far i have tried this.
C# WebMethod
[HttpPost]
public void Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
file.SaveAs(path);
}
}`
Ajax Request
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
in ajax call you have to delete dataType: json because files must be sent multipart/form-data
function uploadFiles() {
var formData = new FormData();
$.each(files, function (key, value) {
formData.append(key, value);
});
$.ajax({
async: false,
type: 'POST',
url: '/Home.aspx/Upload',
data: formData,
contentType: false,
processData: false,
cache: false,
timeout :5000,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
Please try this code
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
return reader.result;
};
reader.onerror = function (error) {
return '';
};
}
function uploadFiles() {
var files=[];
$.each(files, function (key, value) {
var x=getBase64(value)
if(!!x)
files.push(x);
});
$.ajax({
type: 'POST',
url: '/Home.aspx/Upload',
data: JSON.stringity({files:files}),
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
alert('succes!!');
},
error: function (error) {
alert("errror");
console.log(error);
}
});
}
});
[System.Web.Services.WebMethod]
public static void Upload(string[] files)
{
//Convert base64 to file format and save
}
I am doing a update operation from my web method. What I am doing is I have two text boxes inside my webForm1.aspx page. I am trying to post my these textboxes values to web method so my update operation will run. Below is my code:
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: '{val1:"' + uval1 + '",val2:"' + uval2 + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}
My update procedure is running fine but when I put debugging point on my web method and check parameters values it contain undefined values and don't getting correct values from text boxes. below is my codebehind code. Please help me here.
[WebMethod]
public static bool updateData(string val1,string val2)
{
var db = new dbDataContext();
var query = (from e in db.Employees
where e.ID == up_id
select e).FirstOrDefault();
query.EMP_FNAME = val1;
query.EMP_MNAME = val2;
db.SubmitChanges();
return true;
}
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: {val1: uval1 ,val2: uval2 },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}
and you must have to ensure that passed parameters must match webmethod params in server side.
[WebMethod]
public static bool updateData(string val1,string val2)
{
using (var db = new dbDataContext())
{
var query = (from e in db.Employees
where e.ID == up_id
select e).FirstOrDefault();
query.EMP_FNAME = val1;
query.EMP_MNAME = val2;
db.SubmitChanges();
}
return true;
}
You need to send an array from the data parameter in ajax. Try something like:
var uval1 = $("#up_tb1").val();
var uval2 = $("#up_tb2").val();
function upbtnclicked() {
alert('clicked');
$.ajax({
type: "POST",
url: "WebForm1.aspx/updateData",
data: {val1: uval1 ,val2: uval2 },
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall(response) { console.log(error); }
}
Hi i want to pass the values from jQuery and assign those values to a class model which is used in a method.
Following is my script:
$(document).ready(function(){
$('#BtnSubmit').click(function () {
var CollegeName = $('#TxtCollegeName').val();
var CollegeAddress = $('#TxtCollegeAddress').val();
var pageUrl = '<%=ResolveUrl("~/AddNewCollege.aspx/CreateCollegeData")%>';
$.ajax({
type: 'Post',
url: pageUrl,
data: JSON.stringify({ "CollegeName": CollegeName, "CollegeAddress": CollegeAddress}),
dataType: 'text',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
},
error: function () {
alert("An error occurred.");
}
});
});
});
Below is my Csharp method:
[WebMethod]
public static string CreateCollegeData(CollegeDetails collegeDetails)
{
CollegeDAL obj = new CollegeDAL();
bool b = obj.InsertCollegeDetails(collegeDetails);
return "success";
}
But debugger is unable to call the web method. Every time the following message is coming:
Try declaring your object ahead of time: link
I got another solution.
$('#BtnSubmit').click(function () {
var collegeDetails = {};
collegeDetails.CollegeName = $('#TxtCollegeName').val();
collegeDetails.CollegeAddress = $('#TxtCollegeAddress').val();
$.ajax({
type: 'POST',
url: 'AddNewCollege.aspx/CreateCollegeData',
data: "{collegeDetails:" + JSON.stringify(collegeDetails) + "}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (response) {
$('#lblResult').html('Inserted Successfully');
$('#TxtCollegeName').val('');
$('#TxtCollegeAddress').val('');
},
error: function () {
alert("An error occurred.");
}
});
});
I'm trying to pass a string in code behind method using ajax jquery but getting a stupid error. If I pass integer only then it works fine but in case of string it's not working
this is what i've tried
csharp code
public static string GetQuickVD(string key)
{
return key.ToString();
}
jquery
$(document).ready(function () {
GetQuickVL();
});
function GetQuickVL() {
var Nid = new Array();
for (var key in localStorage) {
if (key.substring(0, 4) == "vhs-") {
Nid += key.replace('vhs-', '') + ",";
}
}
$.ajax({
type: "POST",
url: "QuickViewList.aspx/GetQuickVD",
data: '{key: ' +'345,' + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.response);
},
error: function (response) {
alert(response.error);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
use like this
data: {key: "345" }
You can also use like,
type: "GET",
url: "QuickViewList.aspx/GetQuickVD?key=355",
Edit
data: JSON.stringify({"key": "345"}),
And i have the following code
self.upload = function (file) {
var path = $('#fileUpload').val();
var fr= new FileReader();
var ID = JSON.stringify({
ID:23,
Name: file.name,
Type: file.type,
Size: file.size,
Path: path,
data:fr.readAsDataURL(file),
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/files",
type: "POST",
dataType: "json",
data: ID,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
im performing file upload . and my controller is
[HttpPost]
public string upload(filesUpload f)
{
byte[] jj = f.data; // **getting null here**
string givenId = f.Path;
return givenId;
}
when i execute this and upload a file im getting null file data . where filesUpload is my model
what went wrong in my code . Im using Knockout.js for viwe and drundal SPA framework
is there any other way to do . kindly help me
FileReader.readAsDataURL reads the file asyncronically and return nothing. You should at first start read the file, then catch fr.onload event and from here create your json object and call ajax.
upd: The code will look like this:
self.upload = function (file) {
var path = $('#fileUpload').val();
var fr= new FileReader();
fr.onload = function (frEvent) {
var ID = JSON.stringify({
ID:23,
Name: file.name,
Type: file.type,
Size: file.size,
Path: path,
data:frEvent.target.result,
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/files",
type: "POST",
dataType: "json",
data: ID,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert("Data Returned: " + JSON.stringify(json));
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
};
fr.readAsDataURL(file);
};