JSON Invalide primitive - c#

I want to passing my number of seat to TryJSIN.aspx in function test().
but I have error, when I use type 'GET' then I have error
"Invalid JSON primitive: 1-9."
1-9 is noSeat value.
but when I change to 'POST' I have error
An attempt was made to call the method 'test' using a POST request, which is not allowed.
please check my following code. This is when I use get type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "GET",
data: {noSeat: sid},
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this following ajax when I use POST type
var sid = jQuery(this).attr('id');
$.ajax({
url: "TryJSON.aspx/test",
type: "POST",
data: JSON.stringify({'noSeat': sid}),
contentType: "application/json; charset=utf-8",
success: function (response) {
// var arr = JSON.parse(response.d);
console.log(arr);
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
});
and this is my c# code
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
return noSeat;
}
Please help me. I'm pretty new in c# ajax and jQuery. so I need a lot of help
UPDATE:
I Edit my code after first comment. but it show the same.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(noSeat).ToString();
}

When I use POST, I not allowed to use [ScriptMethod(UseHttpGet = true)] because it for GET type. then the data must use JSON.stringify when I use contentType: "application/json; charset=utf-8" because it thinks that I send JSON whereas I send string data. so I need to convert it to JSON first.
var sid = jQuery(this).attr('id');
//console.log(sid);
$.ajax({
url: "TryJSON.aspx/test",
type: "post",
data: JSON.stringify({ 'noSeat': sid }),
contentType: "application/json; charset=utf-8",
success: function (response) {
var arr = JSON.parse(response.d);
objData = new Array();
objData = arr;
for (i = 0; i < objData.length; i++)
{
alert(objData[i].noBooking +" "+ objData[i].noSeat);
}
},
error: function () {
alert("sorry, there was a problem!");
console.log("error");
},
complete: function () {
console.log("completed");
}
this is how to solve on C#
[WebMethod]
// [ScriptMethod(UseHttpGet = true)]
public static string test(string noSeat)
{
SqlConnection conn = DBConnection.getConnection();
SqlCommand cmd;
SqlDataReader dr;
conn.Open();
string sql = "Select noBooking,noSeat FROM booking WHERE noSeat = '" + noSeat +"' AND statusBooked = 1";
cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
List<booking> BookList = new List<booking>();
while (dr.Read())
{
booking bookClass = new booking();
bookClass.noBooking =(int)dr[0];
bookClass.noSeat = dr[1].ToString();
BookList.Add(bookClass);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(BookList).ToString();
}

Related

Auto map JSON AJAX returned data to table row in Jquery/JavaScript

Ok I have created a tab with a table inside of it as follows -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST", url: "../WebMethods/MarketPersuitMethods.aspx/GetColumnHeaders",
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$tbody.append("<th>" + value.ColumnsName + "</th>");
});
$tbody.append('<tr />').children('tr:last')
setTimeout(function () {
}, 1000);
}
});
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
//$table.appendTo('#TabbedMktList');
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
Here is my C# Code
[WebMethod(EnableSession = true)]
public static string GetQueryInfo()
{
String daresult = null;
DataTable yourDatable = new DataTable();
string strConnString = WebConfigurationManager.ConnectionStrings["TimeClock"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandText = "select * from OCI_TEXT_PROJECT_MASTER where proj_id=2049";
da.SelectCommand = cmd;
cmd.CommandTimeout = 30;
cmd.Connection = con;
con.Open();
da.Fill(yourDatable);
daresult = DataSetToJSON(yourDatable);
return daresult;
}
public static string DataSetToJSON(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table);
return JSONString;
}
It is creating the column headers as I wish for it to do. However, I need to populate all the JSON data for the rows below it. I would not know the column headers as they can change.
I am able to see my results are coming back in JSON data -
[{"Project ID":"18180","OPRN":null,"Proj_Type":"2049","Client Name":null,"client_id":null,"ClientContact":null,"Contact_ID":null,"PN":null,"CompleteDate":"2020-05-21T00:00:00","cost":null,"SQFT":2000,"BIM":null,"LEED":"NO ","Delivery_Meth":"Corey ","City":"Orlando","State":"FL ","County":"Orange","IT":"1141","Project Name":null,"Address":"1234. Orlando Ave","zip":"12345","notes":"<p class=\"MsoNormal\"><b>EXTRA TESTING 1-2-3-43</b></p>","PM":"1141","OLDOWNER":null,"Owner_Contact":null,"ProjectManager":"Corey ","Architect":"Collier Health Services","ContractorORG":"BVW Development","ArchitectID":929,"PNAME":"OCI DYNAMICS CRM PROJECT MANAGEMENT SOFTWARE","PROJ_ID":2049,"Office":"Maitland","MPROJECT":null,"Contractor":930,"addr2":"","PROJSTATUS":2,"TotalProjectTime":null,"corp":"0","ProjectStatus":"Construction","TotalDesignTime":null,"OFFNUM":1,"Owner":null,"ProjectType":null,"MarketSector":"FINANCIAL","users":"1141","team":null,"BuildingType":null,"ETA":null,"designstartdate":null,"FINALCONTRUCT":24000.0000,"ESTCONSTRUCT":15000.0000,"Units":"12","WebType":"P","RequestedBy":null,"RequestedDate":null,"Status":"Interview","RFPDATE":null,"SENTDATE":null,"InterviewDate":null,"OCIDATE":null,"Method":null,"ContractType":"0","ContractName":null,"Tags":"CRM FINANCIAL NewTest rigtest2","TotalProfit/Loss":3,"Disciplines":"Mechanical, CAD, Clerical, QA/QC, Project Management","ChillerType":"1","Revit":"2017","Tons":145,"Rooms":5}]
However -
I have no idea where to get it to map over automatically.
I would ideally think somehow to map it based on the TH header text because they would be the same.
My issue is somewhere in here
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
Figured it out -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (d) {
var data = $.parseJSON(d.d);
var colHeader = Object.keys(data[0]);
for (var i = 0; i < colHeader.length; i++) {
$tbody.append("<th>" + colHeader[i] + "</th>");
}
//sets new line
$tbody.append('<tr />').children('tr:last')
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < colHeader.length; j++) {
$tbody.append('<td>' + data[i][colHeader[j]] + '</td>');
}
$tbody.append('<tr />').children('tr:last')
}
setTimeout(function () {
}, 1000);
}
});
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}

How to send multiple data in single FormData object in Ajax?

My application has multiple data like Text-box value, label value, Drop-Down value,File Data and send same data at server side and store in database
To achieve this, i have used below method but now i want to use Formdata and append each value and send it to server side
How to achieve this scenario using Formdata with specific object type.
Below is the code
var selectedText = $('#Commentinput').text();
$('#actioncomments').text(selectedText);
var debitEntityValue = $('#DrAccount option:selected').text();
var creditEntityValue = $('#CrAccount option:selected').text();
var amount = $("#Amountinput").val();
var paymentActionReason = $('#action').text();
var paymentCommentReason = $('#Commentinput').val();
var prepayAccountId =#Model.prepaidBranchList.PrepaidID;
var transactionDate = '#DateTime.Today';
var transactionExtensions = "1";
var fileBase64Data = $("#fileUpload").text();
if ($('#Commentinput').val() == "") {
paymentCommentReason = "No Comment";
}
else {
paymentCommentReason = $('#Commentinput').val();
}
var adjustmentTransactioninfo =
{
PaymentReasonMasterId: paymentReasonMasterId,
DebitEntityValue: debitEntityValue,
CreditEntityValue: creditEntityValue,
Amount: amount,
PaymentActionReason: paymentActionReason,
PaymentCommentReason: paymentCommentReason,
PrepayAccountId: prepayAccountId,
TransactionDate: transactionDate,
TransactionExtensions: transactionExtensions
};
var data = JSON.stringify({
'adjustmentTransactioninfo': adjustmentTransactioninfo,
'fileData': 0
});
var url = "#Html.Raw(Url.Action("AdjustmentTransaction",
"PrepaidActivity"))";
url += '?branchCode=' + '#Model.prepaidBranchList.IASBranchCode'
$.ajax({
url: url,
traditional: true,
data: data,
enctype:"multipart/form-data",
contentType: "application/json charset=utf-8",
dataType: "json",
type: 'POST',
success: function (data) {
$("#ajaxLoader").show();
if (data != null) {
var ProductActionID = data.SuccessMessage.split(':');
uploadFile.append('ProductActionID' , ProductActionID[1]);
FileUpload(uploadFile);
var dialog = document.querySelector('#Finaldialog');
var ConfirmationScreen = $("<p></p>").text(data.SuccessMessage);
$("#finalmdl-dialog").append(ConfirmationScreen);
dialog.showModal();
dialog.querySelector('button:not([disabled])').addEventListener('click', function() {
dialog.close();
location.reload();
});
}
}
});`
Controller code
public JsonResult AdjustmentTransaction(TraxAdjustmentTransactionInfo adjustmentTransactioninfo, string fileData, string branchCode)
{
PrepaidAdminService.PrepaidAdminDashBoardServiceClient _PrepaidAdminService = new PrepaidAdminService.PrepaidAdminDashBoardServiceClient();
TraxAdjustmentTransactionResult result;
adjustmentTransactioninfo.ProductActionMasterId = Convert.ToInt16(System.Configuration.ConfigurationManager.AppSettings["ProductActionMasterId"]);
adjustmentTransactioninfo.ProductCode = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["ProductCode"]);
adjustmentTransactioninfo.DebitEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.CreditEntityMasterId = TraxEntityType.GPLedgerAccount;
adjustmentTransactioninfo.UserId = Utility.UserID;
adjustmentTransactioninfo.RetailerId = _PrepaidAdminService.GetBranchRetailerId(branchCode);
use serializeArray and can be add the additional data:
var data = $('form').serializeArray();
data.push({name: 'Amit', value: 'love'});
$.ajax({
type: "POST",
url: "url",
data: data,
success: function(data) {
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
Remove the #Html.Raw(Url.Action()), contentType and JSON.stringify() and leave that to the ModelBinder. Change your ajax to this:
$.ajax({
url: '#Url.Action("AdjustmentTransaction", "PrepaidActivity")',
traditional: true,
data: {
adjustmentTransactioninfo: adjustmentTransactioninfo,
fileData: "0",
branchCode: '#Model.prepaidBranchList.IASBranchCode'
},
enctype: "multipart/form-data",
type: 'POST',
success: function (data) {
alert("success");
}
});
var params = { param1: value, param2: value2}
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../aspxPage.aspx/methodName',
data: JSON.stringify(params),
datatype: 'json',
success: function (data) {
var MethodReturnValue = data.d
},
error: function (xmlhttprequest, textstatus, errorthrown) {
alert(" conection to the server failed ");
}
});
// Param1 and param2 name should be same as method argument

Json Ajax Parameter pass & Webmethod not firing

In my Ajax function i tried to pass a int Parameter to the Webmethod but it's not success.
Here i paste my code
Ajax Function
$('#drpChurchNames').on('change', function () {
//alert($(this).val());
LoadFathersToChurch(churchId)
});
function LoadFathersToChurch(churchId) {
var url = '<%=ResolveUrl("WebMethods.aspx/GetFatherNames") %>';
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ Id: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
}
Here is my WebMethod
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static List<FatherNames> GetFatherNames(int ChurchId)
{
List<FatherNames> FathersList = new List<FatherNames>();
try
{
SqlCommand comChurchNames = new SqlCommand("GetFathers", conDB);
comChurchNames.CommandType = CommandType.StoredProcedure;
comChurchNames.Parameters.Add("#Id", SqlDbType.Int);
comChurchNames.Parameters["#Id"].Value = ChurchId;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
SqlDataReader rdr = comChurchNames.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
FathersList.Add(new FatherNames
{
Id = (int)r["Id"],
FatherName = r["FatherName"].ToString()
});
}
}
Here is my SP
ALTER PROCEDURE [dbo].[GetFathers]
#SelectIndexName int
AS
BEGIN
Select * from dbo.RevFathers
Where ChurchId = #SelectIndexName
END
You are passing Id as parameter and the correct is ChurchId just like webmethod signature GetFatherNames(int ChurchId).
There is the correct way:
$.ajax({
url: url,
type: "GET",
dataType: "json",
data:'{ ChurchId: " '+churchId +' "}',
contentType: "application/json; charset=utf-8",
success: function (Result) {
$.each(Result.d, function (key, value) {
$("#drprevfather").append($("<option></option>").val
(value.Id).html(value.FatherName));
});
},
error: function (e, x) {
alert(x.ResponseText);
}
});
Is your webmethod actually getting executed? If it is and you think it should be returning data, it could be that your webmethod is not returning JSON, thus jQuery may be generating and error and not firing success.
I have this in my global.asax to configure the output for both XML and JSON:
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
Placed in app_start
GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "json", new MediaTypeHeaderValue("application/json")));
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("type", "xml", new MediaTypeHeaderValue("application/xml")));
I know this isn't a direct answer, but I can't post comments yet so I would have just asked the above question first about is the webmthod getting called.

Pass paramater to webservice on ajax

I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',

pass to javascript class object is serialized in code behind

JavaScriptSerializer jss = new JavaScriptSerializer();
var seferim = jss.Serialize(sefer);
string asds = seferim.ToString();
asds = HttpUtility.HtmlEncode(asds);
function otobusGetir(id, b, i) {
id = encodeURI(id);
$.ajax({
type: 'POST',
url: 'BiletSatis.aspx/Getir',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: '{"id":"' + id + '","Binis":"' + b + '","Inis":"' + i + '"}',
success: function () { },
error: function () { }
})
[WebMethod]
public static string Getir(string id, string Binis, string Inis)
{
string a = id;
string b = HttpUtility.HtmlDecode(id);
return null;
}
The problem is javascript function cannot take parameter(Uncaught SyntaxError: Unexpected token ILLEGAL) which is serialized.How i can totally done tihs job?
The problem is that this is not working while javascript function run it can not take argument,how can totaly don this job
Try like this:
function otobusGetir(id, b, i) {
$.ajax({
type: 'POST',
url: 'BiletSatis.aspx/Getir',
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: JSON.stringify({ id: id, Binis: b, Inis: i }),
success: function () { },
error: function () { }
});
}
and to call the function:
otobusGetir(123, 'foo bar', 'baz');
and the page method:
[WebMethod]
public static string Getir(string id, string Binis, string Inis)
{
// don't use any Html decoding here. The parameters will
// already be properly formatted so you can use them directly
return null;
}

Categories

Resources