Presently I am having the issue of trying to pass information back to the behind code, in this case a user selected name from a list. I have tried setting the data VN to an object and passing that, but that did not work either. Presently it seems to never send it to the behind code as it errors out instead. An example value for VN is: "Location1 Building"
This worked fine when the data part of the AJAX call wasn't used and the query was hardcoded into the behind code. I believe I am misunderstanding exactly how this functions. I have read over 8 similar threads but the fixes on those didn't quite work here either and lead to errors also listed below.
JAVASCRIPT
$("#btnClient_Report").click("click", function CallService() {
var Cn = document.getElementById('client_input');
var VN = Cn.value;
alert("C1 Name: " + VN);
$.ajax({
traditional: true,
type: "POST",
url: '/ClientChart.aspx/Getdata',
data: JSON.stringify(VN),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert("Success: " + msg.d);
CCData = msg.d;
bindClientChart();
},
error: function(ermsg){
alert(ermsg.responseText);
}
});
});
BEHIND CODE - C#
[WebMethod]
public static string[] Getdata(string VN) //test the connection and rerieve data requested.
{
var loc_name = VN;
//connect to DB and query more info.
At present the error is "Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic/IDictonary'2..."
though attempting to change the ajax data to VN from JSON.stringify(VN) leads to
"INVALID JSON Primitive" error.
Attempting to change VN to a simple object like var VN = { ID:[Cn.value]}; leads to a similar error.
The jquery $.AJAX function documentation says is accepts type string, so I would like to learn about how I am messing up and understand this better. Thank you for any and all help!
After trial and error I learned my mistake was that the ajax data line needed to be:
data: '{VN:"' + $("#client_input").val() + '"}',
Inserting the string alone doesn't work properly as it needs the identifier even if you try passing a string as the same identifier name. Hop this may help someone in future learn from my foolish mistake
Do Something like this to Pass string to method..
$.ajax({
type: "POST",
url: "ClientChart.aspx/Getdata",
contentType: "application/json; charset=utf-8",
data: "{'VN':'" + VN + "'}",
async: true,
cache: true,
dataType: "json",
success: function (data) {
alert("Success: " + data.d);
bindClientChart();
},
error: function(ermsg){
debugger;
alert(ermsg.d);
}
});
Related
I've made an ajax call which has returned a json string from a .Net JsonConvert.SerializeObject() call, the json is automatically parsed into an object at the browser but I am currently unable to access the properties without "undefined" being returned.
My current json string being returned is (removed bulk of byte array):
"[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
I've validated this and it's all fine.
My javascript is:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" + data.extfile + "'");
}
}
});
}
I have made sure it is definitely an object. I've tried accessing as data.extfile, data["extfile"], passing extfile in as a byte array and then accessing that but it is always coming up as "undefined". In desperation I even tried accessing indexes, iterating through the object etc. and still nothing.
I have a feeling that there is an issue in the json string which is preventing it from converting properly but I can't see it as I haven't worked much with json. Could someone point out where I'm going wrong?
Solution
Javascript was parsing the response into an object with a single property "data.d", parsed data.d and that created the object correctly.
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data != null && data.d != null) {
let imgData = JSON.parse(data.d);
$("#ImgItem").attr("src", "data:image/png;base64," + imgData[0].extfile);
}
}
});
}
basically if the string that you pasted is the response (data), when using JSON.parse() it converts into an array , so you should use it like that.
const stringResponse = "[{\"filename\":\"\",\"size\":6,\"csize\":\" 5.85 KB\",\"extfile\":\"/9j/4AAQSkZJRgABAQEASABIAAD/2wBDA....AAAAAAAAAAAf//Z\"}]"
const parsedResponse = JSON.parse(stringResponse);
console.log(parsedResponse)
const entry = parsedResponse[0];
console.log(entry.extfile)
so basically, you need to do:
data[0].extfile
Since the console.log(data) statement returns:
{d: "[{"filename":"","size":6,"csize":" 5.85 KB",…AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf//Z"}]"}
The data you are actually trying to obtain is contained in a JSON string contained in the d property of the data received. If you were to parse the string and then access the extfile property you would have your data:
var actualData= JSON.parse(data.d);
var extfile = actualData[0].extfile;
Don't know if this will help but here it is:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
http://api.jquery.com/jquery.ajax/
Also the data is an Array, maybe grab the first object in the array data[0].extfile.
I'm thinking it maybe reworked as such:
function GetItemImage() {
let kditem = $("#txtItem").text();
let url = GetUrl();
$.ajax({
url: url,
type: "POST",
data: JSON.stringify({
"kditem": kditem
}),
dataType: "json",
contentType: "application/json; charset=utf-8"
}).done(function(data){
if (data != null) {
$("#ImgItem").attr("src", "data:image/png;base64,'" +
data[0].extfile + "'");
}
});
}
I want to get value from JSON.stringify(data) to textbox but it showing Uncaught ReferenceError error in window console browser. I am confusing that when I am doing alert to the JSON.stringify(data) at that time it shows the value in alert while when I insert that value from JSON.stringify(data) to the textbox at that time it shows the Uncaught ReferenceError in window console browser.
Here is my code
function blurFunction() {
var c = $find("<%=dropdwn_consignor.ClientID %>");
$.ajax({
type: "POST",
url: "Booking123.aspx/GetCnorGSTNo",
data: "{ Param1: '" + c.get_textBoxControl().value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (data) {
alert(document.getElementById("#<%=txtbx_cnortin.ClientID%>") = JSON.stringify(data));
},
error: function () {
alert("something went wrong...!!!");
}
});
}
Please help me to solve this issues.
Thank You.
Use value property to assign a value. Dont use # in getElementById() use # in jquery
document.getElementById("<%=txtbx_cnortin.ClientID%>").value = data.D;
OR
Just use jquery
$("#<%=txtbx_cnortin.ClientID%>").value =data.D;
You need to set value and get rid of alert() its not a debugging tool
document.getElementById("#<%=txtbx_cnortin.ClientID%>").value = JSON.stringify(data)
instead of
document.getElementById("#<%=txtbx_cnortin.ClientID%>") = JSON.stringify(data);
As you are using jQuery use
$("#<%=txtbx_cnortin.ClientID%>").val(JSON.stringify(data))
I'll try to explain the best I can
this is a .net application
I have a javascript function that calls a webmethod, and that method should return some results
I get response as multiple objects, with param_name and param_value (number of objects and different param_names depends on the request)
now I am having trouble with displaying that data on the page, currently I am trying to return results as a list of dictionaries but don't really now how to go through that and show it on page (I am used to work with datatables and grid, but didn't find a way to work with that and javascript/ajax yet)
i would like results to be shown in something like this
param_name1 param_name2 param_name3
parav_value1 param_value2 parav_value3
parav_value1 param_value2 parav_value3
parav_value1 param_value2 parav_value3
ajax
$.ajax({
type: "POST",
url: 'Reports.aspx/getReport',
data: "{'jsonObject':'" + rp + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
alert('success');
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
});
after this alert i should go through the results and show them
any suggestion is welcome, if there is some easier way I will be glad to listen to it
I'm getting a ParseError even though my JSON validates on jsonlint.com.
Here is the jQuery code:
$.ajax({
url: path,
type: 'GET',
data: {},
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var a = 'breakpoint here doesn't activate';
},
error: function (x, y, z) {
var b = 'code execution stops at a breakpoint here.';
}
});
Here is the PHP code that is being called:
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
$encodedData = json_encode($testData);
echo $encodedData;
return;
}
This comes back to a breakpoint set in the error: function of my .ajax call. Parameter Y is set to "parseerror", and x.responseText =
["testing123"]
I've been looking into this for hours so far. I've looked at many relevant StackOverflow posts, but none have solutions that work in this case.
How can I get a success response from this .ajax call?
Thanks very much in advance to all for any info.
There's nothing visibly wrong with your code, and it works fine when I try it on my local machine. However, your comment above is a big clue:
I just looked at the z param in the Safari console, and found this:"undefined is not a function (evaluating 'JSON.parse(a+"")')" How could that be happening?
It could happen if some code somewhere uses "JSON" as a global variable name, hiding the built-in window.JSON object.
Check for Notice or Warning in your php code, if their is any then remove that and then try. Hop this will help you.
JavaScript allows either single or double quotes for strings, but JSON only allows double quotes. See http://www.json.org/
See also jQuery.parseJSON single quote vs double quote
Just Use
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
echo json_encode($testData);
}
Then in your AJAX you can do
$.ajax({
url: path,
type: 'GET',
dataType: 'json'
success: function(data){
for (var i = 0; i < data.length; i++) {
//DO YOUR STUFF
}
}
});
Please use
$.ajax({
url: path,
type: 'GET',
cache: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
var a = 'breakpoint here doesn\'t activate';
},
error: function (x, y, z) {
var b = 'code execution stops at a breakpoint here.';
}
});
and in your PHP CODE Paste this code.
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
$encodedData = $testData;
echo json_encode($encodedData);
exit;
}
May be after digging more in your code I assume that in your PHP code you were not passing data properly. Please use exit or die method to pass data back to ajax. Please check.
Try with the below code,
function getAllAnswersToHitViaAjax($theJobName) {
$testData[0] = 'testing123';
echo json_encode($testData);
die();
}
$.ajax({
url: path,
type: 'GET',
dataType: 'json'
success: function(data){
console.log(data);
var result = JSON.parse(data);
console.log(result);
}
});
I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)