Passing string array from ASP.NET to JavaScript - javascript

I am trying to call the server side from JavaScript and then pass a string array back to JavaScript, but running into problems.
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
On the ASP.Net server side, I have:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
I am probably mixing things up, as I am still new to JSON.
UPDATE with error code:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript runtime error: Invalid character
Stack trace:
parse JSON[jquery-1.7.2.min.js] Line 2
What is my problem?

I modified your ajax call script to :
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
Note that I added contentType: 'application/json' and changed
var responseArray = JSON.parse(data.response);
to
var responseArray = JSON.parse(data.d);

This s purely out of guess work. But see if this is what you are getting:-
In your Ajax call, your data type is json and looking at the method you are returning a json string. So you do not need to do JSON.parse(data.response). Instead just see if the below works for you. Also i dont see a response object in your Json, instead it is just an array. So it must be trying to parse undefined
var strHeader = data[0];
var strBody = data[1];

Related

JSON POST Import

I am trying to import data from a JSON POST API into a Google Sheet. I have been able to log the full JSON response but now can't filter it to just the attribute that I require as I keep getting an error saying that the attribute is 'undefined' when I try to log DIV1. I have tried testing it for other parameters such as the DrawDate and DrawType, but keep getting the same message.
function main() {
// Make a POST request with a JSON payload.
var data = {
'CompanyId': 'GoldenCasket',
'MaxDrawCount': 1,
'OptionalProductFilter':['OzLotto']};
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)};
var response = UrlFetchApp.fetch('https://data.api.thelott.com/sales/vmax/web/data/lotto/opendraws', options);
Logger.log('output: '+ response);
var json = JSON.parse(response)
var DIV1 = json["Div1Amount"];
Logger.log(DIV1)
}
I am getting this response to the request, but I would like to receive just the Div1Amount.
output:
{
"Draws":[
{
"ProductId":"OzLotto",
"DrawNumber":1323,
"DrawDisplayName":"Oz Lotto $80,000,000",
"DrawDate":"2019-06-25T00:00:00",
"DrawLogoUrl":"http://media.tatts.com/TattsServices/Lotto/Products/OzLotto_v1.png",
"DrawType":"Jackpot",
"Div1Amount":80000000.0000,
"IsDiv1Estimated":false,
"IsDiv1Unknown":false,
"DrawCloseDateTimeUTC":"2019-06-25T09:35:00",
"DrawEndSellDateTimeUTC":"2019-06-25T09:30:00",
"DrawCountDownTimerSeconds":538150.0
}
],
"ErrorInfo":null,
"Success":true
}
In your response, Div1Amount is inisde Draws list. So, to do that, you have to get the list and iterate through the list then var DIV1 = listObj["Div1Amount"]; will work. Sample code:
//after `var json = JSON.parse(response)` line, change your code with this:
var drawList=json ["Draws"];
//now iterate the list:
for(var i=0;i<drawList.length;i++)
{
var DIV1=drawList[i]["Div1Amount"];
console.log(DIV1);
}

jQuery Ajax Input Text and File can't get the value after processing to success function

I have jQuery input text and input file submit using ajax.
$("#uploadForm").on('submit',(function(e)
{
e.preventDefault();
var badgeID = $("#badgeID").val();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var emailAddress = $("#emailAddress").val();
var firstNameMask = $("#firstNameMask").val();
var lastNameMask = $("#lastNameMask").val();
var emailAddressMask = $("#emailAddressMask").val();
$.ajax(
{
url: "updateAccountSetting.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
alert(data.firstNameVal);
$("#firstNameMask").val(data.firstNameVal);
$("#lastNameMask").val(data.lastNameVal);
$("#emailAddressMask").val(data.emailAddressVal);
$(".firstName").html(data.firstNameVal);
$("#btnUpdateAvatar").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');
$('#firstName, #lastName, #emailAddress').attr('readonly', false);
$('.uploadSuccess').show();
$("#btnUpdateAvatar").attr('disabled', true).addClass('btn_inact').removeClass('btn_act');
}
});
}));
I have tried the above code until processing to PHP file and it's working perfect.
But why I can't get value when I try to:
alert(data.firstNameVal);
The result of the alert is : undefined.
If I alert only data
alert(data);
the result is:
Try this:
success: function(data)
{
var result = JSON.parse(data);
alert(result.firstNameVal);
// rest of your code
}
Explanation:
For JS it is just a string what you get. You have to convert it to JSON-Object.
You may solve adding the correct header information in PHP or parsing the response in JavaScript.
PHP solution: add this row before output (on top of your script, maybe)
header('Content-Type: application/json');
JS solution: parse response string as json:
var dataObj = JSON.parse(data);
You get JSON response from updateAccountSetting.php url. JSON (JavaScript Object Notation) is a lightweight data-interchange format. You have to convert JSON data to Javascript object.
Have a look at below
success: function(data)
{
var data =$.parseJSON(data);//convert json data to javascript object
$("#firstNameMask").val(data.firstNameVal);
$("#lastNameMask").val(data.lastNameVal);
$("#emailAddressMask").val(data.emailAddressVal);
$(".firstName").html(data.firstNameVal);
$("#btnUpdateAvatar").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');
$('#firstName, #lastName, #emailAddress').attr('readonly', false);
$('.uploadSuccess').show();
$("#btnUpdateAvatar").attr('disabled', true).addClass('btn_inact').removeClass('btn_act');
}

Unable to receive POST body from Ajax request using Play Framework

I am trying to send a POST request to my backend with some JSON data. The call from the frontend looks like this:
function register() {
var user = $("#form_reg_username").val();
var pass = $("#form_reg_password").val();
var referal = $("#form_reg_referal").val();
var postbody = {};
var url = "http://" + location.host + "/api/admin/register";
postbody.username = user;
postbody.password = pass;
postbody.referal = referal;
var jsonbody = JSON.stringify(postbody);
console.log(jsonbody);
$.ajax({
type: "POST",
url: url,
data: jsonbody,
dataType: "json",
success: registerHandler()
});
}
The generated log looks like this:
{"username":"jakob","password":"11111","referal":"urgotislove"}
Which is fine.
Here is the start of how I handle the request on the backend (I am using play 2.4)
public Result adminRegister() {
// Generate JSON from postbody
ObjectNode json = Json.newObject();
Logger.info("Body: " + request().body().asText());
JsonNode body = request().body().asJson();
String username = body.get("username").asText();
String password = body.get("password").asText();
String referal = body.get("referal").asText();
...
}
Looking at my application log the Info log looks like this:
[info] application - Body: null
I am then getting a Nullpointer Exception in first line of trying to get the json values.
So for some reason the POST body seems not to be received correctly.
Thanks for any help in advance.
Turns out the Postbody was transferred correctly but for some reason the .asText() as well as the .asJson() method, did not work correctly and returned null.
I fixed my issue with this little workaround:
Http.RequestBody requestBody = request().body();
Map<String, String[]> body = requestBody.asFormUrlEncoded();
String username = body.get("username")[0];
String password = body.get("password")[0];
String referal = body.get("referal")[0];

json data extraction in pebbleJS

I am stuck in json data extraction in pebble.
var UI = require('ui');
var ajax = require('ajax');
var URL="http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=4a9f5581a9cdf20a699f540ac52a95c9&limit=10&format=json&callback=?";
var card = new UI.Card({
title:'last.fm stat',
subtitle:'Fetching...'
});
card.show();
ajax({ url: URL }, function(data){
var topArtist=data.topartists[0].artist.name;
card.subtitle(topArtist);
});
Here's the error I get:
[INFO] ocess_manager.c:368: Heap Usage for App <lastfm sta: Total Size <48584B> Used <6256B> Still allocated <28B>
[PHONE] pebble-app.js:?: (+) [card 1] : [card 1]
[PHONE] pebble-app.js:?: JavaScript Error:
TypeError: Cannot read property '0' of undefined
at pebble-js-app.js:123:32
at pebble-js-app.js:871:17
at req.onreadystatechange (lib/ajax.js:11
4:9)
Evening Mona,
Remove the question mark at the URL's end.
Remove the card.show() instruction where you put it, and place it after adding a subtitle to it.
Specify you're dealing with a JSON datatype.
And your final code should now look like this:
var UI = require('ui');
var ajax = require('ajax');
var URL="http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=test&api_key=4a9f5581a9cdf20a699f540ac52a95c9&limit=10&format=json&callback=";
var card = new UI.Card({
title:'last.fm stat',
subtitle:'Fetching...'
});
ajax({ url: URL, type: 'json' }, function(data) {
var topArtist = data.topartists.artist[0].name;
card.subtitle(topArtist);
card.show();
});
It should now run perfectly. :)
Also, you should add a failure callback in your ajax method:
ajax({object}, success, failure)

Posting multiple objects in an ajax call

I have a list of data which is within multiple objects.
Each object has an ID and a status and then the main object has a type and a form id.
The problem I am having is posting result via ajax as it doesn't like the multiple objects.
This is the code I have:
var permissionsData = [];
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData.push(obj);
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: permissionsData
});
How can I wrap/send permission data?
How about changing your array to an object and using jQuery's param function.
var permissionsData = {};
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData[index] = obj;
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: $.param(permissionsData)
});
maybe you can use json2.js
it can parse the object to json string and parse the json string to object
you can use JSON.stringify method for parse object to json string

Categories

Resources