jsonp syntax error unexpected token - jsonp

if I use dataType: json I don't get an error in the response/
If I use dataType: jsonp I get the following error:
syntax error unexpected token
This is my jquery code
function testJsonp()
{
$.ajax({
type: "POST",
url: "http://localhost/FT8Services/FTService.asmx/testjsonp",
data: "{firstname: '" + encodeURIComponent("Stack") + "', lastname: '" + encodeURIComponent("Overflow") + "'}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (result) {
var loginfo = eval(result.d);
alert(loginfo[0]);
if(loginfo.length > 1)
{
alert("Sucess");
}
else
{
alert("no access");
}
},
error: function(xhr, status, error) {
alert(error);
}
})
}
and this is my asp.net web method
<WebMethod()> _
Public Function testjsonp(ByVal firstname As String, ByVal lastname As String) As String
Dim rdatas As New List(Of String)
Dim fullname As String = firstname & lastname
For i As Integer = 1 To 5
rdatas.Add(fullname & " " & i.ToString)
Next
Dim js As New JavaScriptSerializer
Dim strJSON As String = js.Serialize(rdatas.ToArray)
Return strJSON
End Function

Related

Is 'var' a reserved word in VB.NET?

While running the following code below, I received the following error:
Type 'var' is not defined.
Is 'var' a reserved word in VB.NET?
If not, why am I getting this error and how do I resolve it?
<WebMethod()> _
Public Shared Function SaveData(empdata As String) As String
Dim serializeData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)
Using con = New SqlConnection(Constr)
For Each data As var In serializeData
Using cmd = New SqlCommand("INSERT INTO Employees VALUES(#Fname, #Lname,#Email,#CreatedDate)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Fname", data.FName)
cmd.Parameters.AddWithValue("#Lname", data.LName)
cmd.Parameters.AddWithValue("#Email", data.EmailId)
cmd.Parameters.AddWithValue("#CreatedDate", DateTime.Now)
cmd.Connection = con
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd.ExecuteNonQuery()
con.Close()
End Using
Next
End Using
Return Nothing
End Function
'Updated:
function getAllEmpData() {
var data = [];
$('tr.data-contact-person').each(function () {
var firstName = $(this).find('.spousename01').val();
var lastName = $(this).find('.spouseaddress01').val();
var emailId = $(this).find('.spouseincome01').val();
var alldata = {
'FName': firstName,
'LName': lastName,
'EmailId': emailId
}
data.push(alldata);
});
console.log(data);
return data;
}
$("#btnSubmit").click(function () {
var data = JSON.stringify(getAllEmpData());
//console.log(data);
$.ajax({
url: 'closures.aspx/SaveData',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
});

My ajax request

Ajax is not populating my table with all the information from json encode values are {"name":"1","...":"Value"} fields with string values and the integers are not.
var idvalue = $("#modal-name"),
$.ajax({
type: "POST",
url: "ajax.php",
data: {
action: "getBudget",
userId : userId
},
success : function(data) {
//parse result as JSON
var res = JSON.parse(data);
//update modal fields
idvalue . text(res.name);
// other ID to populate
}
});
try to remove the space and replace the "," by a ";" in the first line: var idvalue = $("#modal-name");. It will resolve some of your problems.

Cannot load more than 2 files to S3 using plupload

My code below works fine so long as I only load 2 multiple files. If I load 3 or more, every file after the 2nd one does not get added to my s3 bucket (although no error is shown by plupload).
Can anyone understand why?
var uploader = new plupload.Uploader({
browse_button: 'browse', // this can be an id of a DOM element or the DOM element itself
url: 'https://s3.amazonaws.com/mybucket',
filters: {
max_file_size: '25mb',
prevent_duplicates: true,
multiple_queues: true
}
});
uploader.init();
uploader.bind('FilesAdded', function (up, files) {
plupload.each(files, function (file) {
var myFileName = file.name.toLowerCase();
myFileName = myFileName.replace(/[|&;$%#"<>()+,]/g, "");
var elem = $('#hfReplyGuid');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "WebService.asmx/prepareUpload",
data: "{'acl':'private','bucket':'myBucket','file':'" + folderPath + elem.val() + "_" + myFileName + "'}",
success: function (data) {
params[myFileName] = { policy: data.d[0].Policy, signature: data.d[0].Signature };
var multipart_params = {
'key': folderPath + elem.val() + "_" + myFileName,
'filename': folderPath + elem.val() + "_" + myFileName,
'AWSAccessKeyId': AWSAccessKey,
'acl': 'private',
'signature': params[myFileName]["signature"],
'policy': params[myFileName]["policy"],
'success_action_status': '201'
}
up.setOption('multipart_params', multipart_params);
uploader.start();
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
I solved this by basing code on this post Upload multiple files to Amazon S3 using plupload
However I had to create the policies in the FileFiltered event, start the uploader in the FilesAdded event and then add each policy in the BeforeUpload event as below:
var multipart_params = policies[file.id];
up.setOption('multipart_params', multipart_params);

Jqgrid: Access Selected Row Cell value in Code behind

I want to access the selected row cell id in the code behind. I can do it either by Ajax call but it is not possible when i try to send the data from the Jqgrid Subgrid.
Below is the Subgrid code:
subGridRowExpanded: function (subgrid_id, row_id) {
debugger;
var subgrid_table_id, pager_id; subgrid_table_id = subgrid_id + "_t";
var selected_row_id = $('#tblFormData').jqGrid('getCell', row_id, 'Category_Id')
// pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + pager_id + "' class='scroll'></div>");
$("#" + subgrid_table_id).jqGrid({
// $("#tblTest").jqGrid({
url: "/Forms.aspx/GetFormsData", //?selected_row_id=" + selected_row_id,
data: '{"CategoryDesc":"' + selected_row_id + '"}',
datatype: "json",
contentType: "application/json; charset=utf-8",
loadonce: true,
width: "300",
height: "auto",
pager:"#tblSubpager",
colNames: ['FormName','FormPath'],
colModel: [
{ name: "FormName", index: "FormName", editable: true, formatter: 'showlink' },
//{ name: "FormPath", index: "FormPath", editable: true, hidden: true },
{
name: 'FormPath',
index: 'FormPath',
hidden: true,
enctype: "multipart/form-data",
editable: true,
edittype: 'file',
editrules: {
edithidden: true,
required: true
},
formoptions: {
elmsuffix: '*'
}
}
],
gridview: true,
autoencode: true,
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj.d; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; }
}
});
below is the function which i call it from the URL in Vb.NET.
<WebMethod> _
<ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _
Public Shared Function GetFormsData(CategoryId As String) As List(Of Dictionary(Of String, String))
Using dt As DataTable = DirectCast(DataAccess.ExecuteStoredProcedure("AFI_DYNAMIC", "Ashley.dbo.usp_GetDownloadFormsDetails", DataAccess.StoredProcedureReturnType.DataTable), DataTable)
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows1 As New List(Of Dictionary(Of String, String))()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
Dim row1 As Dictionary(Of String, String)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
row1 = New Dictionary(Of String, String)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
'string sb = "Yahoo!";
Next
rows.Add(row)
'For i As Integer = 0 To dt.Columns.Count - 1
Dim sb As String = "" & dr("FormName").ToString() & ""
'Next
row1.Add(dt.Columns(0).Caption, sb)
rows1.Add(row1)
Next
Return rows1
End Using
End Function
Now i want to Access the CategoryId in my code behind Can anybody help me on this.
The code have clear many problems. I post below some clear problems which I could find by reading of the code:
Is CategoryId the column of the parent grid? Is $('#tblFormData') the parent grid? In the case you could use $(this) instead of $('#tblFormData').
You use pager_id as id of <div> of the pager for subgrid, but the line which assign the value for pager_id is commented and id is undefined. Instead of that you use pager:"#tblSubpager" which is wrong.
jqGrid has no contentType parameter. So you should remove it. Instead of that you use already ajaxGridOptions parameter with contentType. It's correct parameter.
You use data: '{"CategoryDesc":"' + selected_row_id + '"}', but the server code expect parameter with the name CategoryId and not CategoryDesc. By the way jqGrid has no data parameter in case of usage datatype: "json". What you mean should be postData. Correct will be to use
postData: {
CategoryId: selected_row_id
}

How can i read Handsontable array in ASP.Net?

I have an handsontable and i am trying to read the array data in ASP.Net. i have the below code. When i send the data to server. i keep getting ParseError. I tried different ways but did not help.
var data = [
["Year", "Kia", "Nissan", "Toyota", "Honda"],
["2008", 10, 11, 12, 13],
["2009", 20, 11, 14, 13],
["2010", 30, 15, 12, 13]
];
var $container = $("#example1");
$container.handsontable({
data: data
});
function sendData() {
var $container = $("#example1");
var handsontable = $container.data('handsontable');
var myData = handsontable.getData();
$.ajax({
type: "POST",
url: "Test.aspx/SaveUser",
data: "{'data':" + JSON.stringify(myData) + "}",
dataType: "json",
success: function (response) {
alert("Data sent to server.");
window.location.reload();
},
error: function (xhr, status) {
alert("An error occurred: " + status);
}
});
}
Server side code
<WebMethod()> <ScriptMethod()> _
Public Shared Sub SaveUser(data As List(Of String))
Dim lstItems As List(Of Object) = New JavaScriptSerializer().ConvertToType(Of List(Of Object))(data)
End Sub
Please help me in reading the data and thanks in advance
I figured it out. Hope it helps others
just changed the line
data: '{data: ' + JSON.stringify(myData) + '}',