I want to pass some value to server and it has to return one string.
Jquery version
<script src="js/jquery-3.1.1.js"></script>
Here is my code:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx code
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=#UserFileName and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#UserFileName", fileName);
cmd.Parameters.AddWithValue("#ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."
StackTrace:" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".
I think this error it occurs in server side. But I don't know what is that
Updated
Error Message:"Invalid web service call, missing value for parameter:'fileName'."
Send your data like below:
In object format
data: { fileName:fileName },
OR
As a String
data = "fileName="+filename;
After one day I found What was my mistake.
This is the answer
data:'{fileName:"'+fileName+'"}'
Related
I want to fill the DropDownList via SqlQuery in webmethod. But it gives internal Server error.
Except for the error, can't I just do this in javascript?
function doldur() {
$.ajax({
url: "UserServis.asmx/ListDoldur",
type: "post",
dataType: "json",
contentType: "application/json;charset=utf-8",
data: "{ 'sysName': 'Sudio', 'categoryID': " + 544 + " }",
success: function (data) {
var result = data.d;
alert(result);
},
error: function (requeset, status, error) {
alert(error);
}
});
}
[WebMethod(EnableSession = true)]
public static List<string> ListDoldur()
{
List<string> retList = new List<string>();
SqlConnection baglanti = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnLEO"].ConnectionString);
SqlCommand komut = new SqlCommand("select BolumAdi from emre_bolumler ", baglanti);
SqlDataAdapter da;
DataSet ds;
DataTable dt;
baglanti.Open();
da = new SqlDataAdapter(komut);
ds = new DataSet();
da.Fill(ds,"TestTable");
dt = ds.Tables["TestTable"];
for (int i = 0; i < dt.Rows.Count; i++)
{
retList.Add(dt.Rows[i].ItemArray[0].ToString());
}
return retList;
}
Yes you can.
you are sending data to the code behind method but it does not have a parameter to accept data;
I think the simplest way is to serialize your datatable and return a JSON string, not a List<string> (maybe you can do return retList.ToArray() ? not sure);
skip the dataset, just use a table. I'm not entirely sure what's going on with the loop, but I think when you serialize the data you won't have to do that (unless you have a ton of columns to avoid).
using Newtonsoft.Json;
// convert datatable to a string.
string result = JsonConvert.SerializeObject(tbl);
when the data is returned to the ajax method, create the dropdown options.
I'm trying to run a SQL Stored Procedure called UpdateKey that saves a record called Key into the Kiosks table of my database (called MyDB) based on record ID, and then returns it, as below:
USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateKey]
#id uniqueidentifier,
#key nvarchar(8)
AS
BEGIN
SET NOCOUNT ON;
UPDATE [dbo].[Kiosks]
SET session = NEWID(), [key] = #key
WHERE id = #id;
SELECT #key AS kioskKey
END
I'm trying to call it using Ajax and a service file as below:
Javascript:
function updateKeyOnly(index) {
$.ajax({
type: "POST",
url: "../Services/Common.svc/UpdateKey/" + kioskList[index].id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.success == true) {
txtNewKeyDisplay.val(response.keyItem.key); //display new key to user
$('#tblKiosks').dataTable().fnClearTable();
$('#tblKiosks').dataTable().fnDestroy();
loadData();
$(this).dialog("close");
}
else {
alert("updateKeyOnly error" + JSON.stringify(response));
}
}
});
}
Service (in C#):
OperationResponse ICommon.updateKey(string id)
{
string newKey = generateKey();
string result;
Guid newID;
if (Guid.TryParse(id, out newID))
{
try
{
result = myDB.UpdateKey(newID, newKey).FirstOrDefault();
//return new OperationResponse(request.key);
}
catch (Exception ex)
{
if (isDebug() == true)
{
return new OperationResponse(ex.Message);
}
else
{
return new OperationResponse("Error: Database inaccessible.");
}
}
if (result != null)
{
//return new OperationResponse();
resetKeyResponse response = new resetKeyResponse();
response.keyItem = new resetKeyItem();
response.keyItem.key = result.ToString();
return response;
}
else
{
return new OperationResponse("Error: Key cannot be updated or retrieved.");
}
}
else
{
return new OperationResponse("Error: Invalid ID.");
}
}
From the ICommon.cs:
//To Update Kiosk Key
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UpdateKey/{id}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
OperationResponse updateKey(string id);
Currently my problem is that when I running the Ajax, it gives an Error 504 - Receive Failure according to Fiddler, and on my page itself clicking the button that activates the Ajax causes nothing to apparently happen. Despite that however checking the Kiosks table after that shows that the new key is saved into it after all, it's just that the stored proc can't return it to my webpage. Any help is appreciated.
I'm an idiot - I changed all instances of OperationResponse in updateKey to resetKeyResponse after noticing how inconsistent it was, and then it ran.
I use jquery (ajax) to connect to a web service which returns string , it is not working with me. it always go to error function. here is my web service :
[HttpGet]
[ActionName("GetImage")]
public string GetImage(string base64String, string imgName,string reqTitle , string reqSubject, string reqStatus,string Creator , DateTime creationdate )
{
try
{
using (PhMobAppEntities context = new PhMobAppEntities())
{
ClaimsApproval _ca = new ClaimsApproval();
_ca.imageBasestrg = base64String;
_ca.imageName = imgName;
_ca.Creator = Creator;
_ca.CreationTime = creationdate;
_ca.ReqStatus = reqStatus;
_ca.ReqTitle = reqTitle;
_ca.ReqSubject = reqSubject;
context.ClaimsApprovals.Add(_ca);
context.SaveChanges();
return "Success";
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
and here is my js code :
$("#sendphoto").click(function () {
var url = "http://41.128.183.109:1212/api/Data/GetImage";
var data = {
imgName: "test"
};
$.ajax({
url: url,
type: 'Get',
data: data,
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Please Check Your Internet Connection");
}
});
});
It is running ok when i tested my web service in advanced rest client ,please advice .
I tried connecting to your web service and I get the following response:
{"$id":"1","Message":"No HTTP resource was found that matches the request URI 'http://41.128.183.109:1212/api/Data/GetImage'."}
I think what you have is an internal problem with your c# code, probably with your routing. Your javascript call is probably working fine, but you are passing only one parameter, "test" while you have many more in your declaration.
What http response code are you getting?
I'm a bit new in web development and I can't achieve what I'm trying to do.
I have a Database with a table called "PI_Banners", where I store some images. This table stores an ID and a VARBINARY column that contains the binary data of the image.
What I'm trying to do, is to retrieve that data with an Ajax request to a C# function, and create a "img" tag using Data URI Scheme. Then append that new image to a div
This is what I got:
Ajax call:
$(document).ready(function() {
var dto = {};
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'BannerRotativo.aspx/devuelveBanners',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
responsedevuelveBanners(data);
},
error: errorResponse
});
});
Being "devuelveBanners" the C# function.
C# code:
public static string devuelveBanners()
{
DataReader DR;
DR = listaBanners();
//armaJson creates the Json string from the DataReader.
string strJson = GENERAL.armaJson(DR);
return strJson;
}
public DataReader listaBanners()
{
try
{
string strComando;
sqlCommand SQLC;
DataReader DR;
strComando = "SELECT banner_img FROM PI_Banners";
//sqlCon is the connection, and is open already.
SQLC = new System.Data.SqlClient.SqlCommand(strComando, sqlCon);
SQLC.CommandType = CommandType.Text;
DR = SQLC.ExecuteReader();
return DR;
}
catch (Exception ex)
{
throw ex;
}
}
When I parse the Json string back, and create the image:
function responsedevuelveBanners(data)
{
var datos = JSON.parse(data.d);
$("#imgContainer").append("<img src='data:image/jpg;base64," + datos.Rows[0].Row[0].banner_img + "' />");
}
the image is created but doesn't show up, because it has this URL:
data:image/jpg;base64,System.Byte[]
I know I'm doing something terribly wrong trying to retrieve the json data this way, but I don't know how to achieve this!
Thanks in advance!
In order to use <img src="data:image/PNG;base64' the base64 part is because you need to return a Base64 string instead of array of bytes therefore you need to convert your byte[] to 64Base using: Convert.ToBase64String(buffer)
So using your code as example:
ImageConverter imageConverter = new ImageConverter();
byte[] resourceByteArray = (byte[])imageConverter.ConvertTo(_YourObj.GetImage(), typeof(byte[]));
Your WebApi method should be returning:
return Convert.ToBase64String(resourceByteArray);
I'm trying to send a GET request to my localhost via an AJAX call and return the promise object and then play around with it. (The data is coming from a function web service call). I added the following to my web.config file and it seemed to the the 'no get request allowed' error:
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
JS
$(document).ready(function () {
function fetch() {
var data = { firstName: 'd' };
return $.ajax({
url: "../../Service.asmx/GetPersonsByName",
data: JSON.stringify(data),
dataType: "json",
success: function (results) {
console.log(results.d);
},
error: function (xhr, ajaxOptions) {
console.log(xhr);
console.log(ajaxOptions);
}
});
};
fetch().done(function () {
console.log('finished');
}).fail(function () {
//fails
console.log('fails :(');
});
});
With this code I get the error that there's a missing parameter. Web service method for good measure:
[WebMethod]
[ScriptMethod]
public List<Person> GetPersonsByName(string firstName)
{
var personList = new List<Person>();
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spGetPersonsByName", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#firstName", firstName);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Person p = new Person();
p.PersonId = Convert.ToInt32(rdr["PersonId"]);
p.FirstName = rdr["FirstName"].ToString();
p.LastName = rdr["LastName"].ToString();
personList.Add(p);
}
}
}
return personList;
}
The web service works, so what I'm pretty sure is the URL of the webservice that's at fault:
GET http://localhost:58268/Service.asmx/GetPersonsByName?{%22firstName%22:%22d%22} 500 (Internal Server Error).
EDIT: the stored procedure I'm using works.
I tried to append $.param(data) to the URL and that didn't work either. What's the best way to get this working? Should I append the data I want to the URL? Do I need to include it on the AJAX object? I've tried various things with various degrees of non-success and I'm looking for the overarching theme here that I'm not implementing correctly.