An access to list values in AJAX - javascript

There is a request using AJAX. I'm sending data to the server and getting a response. There are no problems with this. But:
alert(response) returns [object Object].
alert(response.data[0]) returns undefined.
function requestFromCalendar() {
var first = selected[0];
var second = selected[1];
first.month = first.month+1;
second.month = second.month+1;
$.ajax({
data: {
first: JSON.stringify(first),
second: JSON.stringify(second)
},
type: 'POST',
dataType: 'json',
url: '/get_selected_values'
}).done(function(response) {
alert(response);
alert(response.data[0]);
})
}
#app.route('/get_selected_values', methods=['POST'])
def get_selected_values():
values = request.form.get("first")
first_date = json.loads(values)
values = request.form.get("second")
second_date = json.loads(values)
t = time(0, 0, 0, 0)
d = date(year=first_date['year'], day=first_date['day'], month=first_date['month'])
start_date = datetime.combine(d, t)
start_date = start_date + timedelta(microseconds=123456)
d = date(year=second_date['year'], day=second_date['day'], month=second_date['month'])
end_date = datetime.combine(d, t)
end_date = end_date + timedelta(microseconds=123432)
data = fetch_selected_date(start_date=start_date, end_date=end_date, login=current_user.get_id())
if data:
return jsonify({'data': data})
return jsonify({'data': []})
What's the matter? How to fix?
EDIT 1
console.log(response) returns {data: Array(0)}
console.log(response.data[0]) returns undefined
EDIT 2
The sending data stores in python code. It is seen in debug mode, so problem is not there for sure

Related

DataSet Value in Jquery C#

I have one page in which, URL contains Querystring Value.
QSecID=164&QTempId=55&QSecName=New%20Temp%20Bt
When the page loads them and tries to get the value it works fine.
$(document).ready(function() {
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var urlName = getUrlParameter('QSecName');
alert(urlName);
getImageData(urlName); //Pass Query String Value to Function
});
Now I am passing this value to C#, ASPX.CS page and try to fetch the data based on QSecName.
But i got error. Here is my Jquery function.
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
//data: '',
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("Success");
alert(JSON.parse(data.d));
}
});
}
My C# Page returns the DataSet in Jquery.
[WebMethod()]
public static string GetImageData(string dataSecName)
//public static string GetRole()
{
clsSection objSectNew = new clsSection();
DataSet DS = new DataSet();
DS = objSectNew.GetImageDataByJQ(dataSecName);
return JsonConvert.SerializeObject(DS);
}
Edit Code 1
Here is my SQL Statement Which is get executed when i run the page and
DS = objSectNew.GetImageDataByJQ(dataSecName);
this method pass the query string value in to execute the Stored Procedure.
select mhp.ImageName,mhp.HotSpotID,imgdetail.XCordinate,imgdetail.YCordinate
from tbl_SOAPDetailsInfo e inner join M_ImageHotSpot mhp on e.ImgHotSpotName=mhp.ImgHotSpotNameByUser
inner join M_ImageHotSpotDetail imgdetail on mhp.HotSpotID=imgdetail.HotspotIDFK where e.SOAP_D_Name='New Temp Bt'
I want to use my XCordinate, YCordinate and ImageName to display image using jquery. but Inside the alert BOX
**[object] [object]**
error display. How can i get and assign this value X AND Y value and display in DIV.
Edit Code 2
ImageName XCordinate YCordinate
$parent in angularjs.png 1146 590
$parent in angularjs.png 1216 588
$parent in angularjs.png 1188 626
$parent in angularjs.png 1162 582
$parent in angularjs.png 1193 586
The Database Value. JSON FORMAT DATA
{"d":"{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"}
So as per your question [object] [object] is not an error. It means you cannot fetch it in a correct manner.
Though I am not sure what kind of data you are sending from your back-end code in data But you could try following way,
var data = "{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
So now if you replace your code with above sample your code should look like below:
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
});
}
Note : Try to debug in browser console you would understand object notation more details.
See the screen shot how would you do that
Hope this would help

AJAX call to async method is success, but data returned is undefined

I have a controller, and when I Debug.WriteLine the data which I'm returning it's exactly like it's supposed to be. I'm very new to async in .NET, but it seems something gets lost between the controller and the view, because the AJAX call is a success, but the data which I'm returning is undefined when I try to work with it.
Below is the method in the controller. Here the data is correct, and as far as I know this method works exactly as it should.
[HttpPost]
public async Task<JsonResult> getServerProcesses(string server)
{
HttpClient client = new HttpClient();
QueryPair<JToken, JToken> processes = new QueryPair<JToken, JToken>();
using (client)
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var processesRequest = ProcessURLAsync(baseUrl + "activityMonitor/" + server + "/processes", client);
HttpResponseMessage response = await processesRequest;
var jsonString = response.Content.ReadAsStringAsync().Result;
JObject json = JObject.Parse(jsonString);
var data = json.SelectToken("Processes" + ".Data");
var columns = json.SelectToken("Processes" + ".Columns");
processes.Data = data;
processes.Columns = columns;
Debug.WriteLine(data);
}
return Json(processes);
}
As you can see I use an alert to confirm the success, but when I try something such as getting the length it says it's undefined. Even when I just try to console.log the object it says it's undefined.
$.ajax({
type: 'POST',
url: '/Home/getServerProcesses',
data: {'server': server},
success: function(data) {
console.log("Length: " + data.length);
alert("oui");
$('#server-name').empty();
$('#server-name').append(server);
var dataTable = new google.visualization.DataTable();
for (var i = 0; i < pmdfields.length; i++) dataTable.addColumn('string', pmdfields[i]);
for (var i = 0; i < data.length; i++) dataTable.addRow(data[i]);
var table = new google.visualization.Table(document.getElementById('processTable'));
table.draw(dataTable, {showRowNumber: true, width: '100%', height: '100%'});
},
error: function(data) {
alert('ajax getServerProcesses POST request error');
}
});
From API. Under response it has an empty JSON object full of empty arrays. I suspect the error is in my controller class:

Using arrays in Ajax

Here is my original code in Javascript
var wt_val = [];
for (i = 0; i<human_wt.length; i++){
var mult;
mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100));
wt_val.push(mult);
}
wt_val is a list or a list of lists.
Now I am sending this to the server.
$.ajax({
type: 'GET',
url: '/add',
data: {hoot: wt_val},
success: function(results){
alert("success");
},
error: function(error) {
}
});
Again, no error here.
But no value is received here.
app.route('/add', methods=['GET'])
def sum():
start = request.form.getlist('hoot[]')
print type(start)
print len(start)
Length is 0
you will need to do something like this
paramtoget= { pval: wt_val};
in your post
$.post('..abc.aspx' + Math.random()
, {
param: paramtoget
}
on server side
var value = Request.Form("param[pval][]")
Hope this helps

Add Property dynamically to the JSON array

I would like to two add property Id and ButtonId to the exisiting json result. I have pasted the below js code for reference and I would like to pass the jsonresult to MVC controller. As of now it returns null. please help to proceed. Thanks.
my final result should look like this
json{"Groups":{"Id":"2","ButtonId":"1142","1186","1189"},
{"Id":"3","ButtonId":"1171","1173","1174","1175","1176","1187"},
{"Id":"4","ButtonId":"1177","1178","1179"}} etc..
var btnlist = {Groups: {Id:"", ButtonId: ""}};
$.each($(".buttonData"), function (index, value) {
var values = value.id.split(':');
grpid = values[0].split('-')[1];
btnid = values[1].split('-')[1];
console.log('grpid=' + grpid + ' btnid=' + btnid);
if (typeof (btnlist['Groups'][grpid]) == 'undefined') {
btnlist['Groups'][grpid] = [];
}
btnlist['Groups'][grpid].push(btnid);
});
$.ajax({
type: "POST",
url: "#Url.Action("Home", "Menu")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(btnlist) ,
success: function (result) {
console.log('json' + JSON.stringify(btnlist));
console.debug(result);
},
error: function (request, error) {
console.debug(error);
}
});
This is the json result before pushing into the multidimensional array
The json result, where the properties Id and ButtonId is inserted behind.
null result passed to the controller
With assistance of my colleague, the desired output is as below. This is for other programmers who face similar issue with JSON array. Thanks.
var btnlist = [];
btngrps = $('.btn-sort-container');
$.each(btngrps, function(k, v) {
btnarr = {};
gid = $(this).attr('id');
grpid = gid.split('-')[1];
btnarr.Id = gid.split('-')[1];
btnobjs = $(v).find('.buttonData');
if (btnobjs.length) {
btnarr['btnId'] = [];
$.each(btnobjs, function(bk, bv) {
btnid = $(bv).attr('id').split('-')[2];
btnarr['btnId'].push($(bv).attr('id').split('-')[2]);
});
console.debug(btnarr);
btnlist.push(btnarr);
}
});
console.debug(btnlist);
Output on console
: http://i.stack.imgur.com/oJ3Dy.png

Cant get ajax response to place nice with python code

Question: For some reason I can't seem to figure out why my ajax call will not return a value for success if my wo_data query comes up empty. What I want to happen is if I put a value into id_work_order and its not found in my db pop up an alert saying workorder was not found- otherwise if it is found return success which works. Any help would be greatly appreciated!
What happens is I get this if a workorder is not found in my browser console
typeerror: data[0] is undefined
if it is found I get this
success
Here is what my data looks like if the workorder is found in my response
0: object
purch_order: "1"
success: "success"
part_rev: "A"
part_number: "12345"
work_o: "W0000001"
customer_name: "TEST"
if it isn't found I get nothing back in my response
here is my views.py
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
for x in wo_data:
x_json = {}
if wo_data.exists():
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)
else:
data = 'fail'
return render(request, 'app/sheet_form_create')
here is my workorder_ajax.js
$(document).ready(function () {
//$('#id_work_order').click(function () {
// getwork();
//});
$('#work_search').click(function () {
pop_other_fields();
});
//function getwork(){
// $('#id_work_order').autocomplete({
// source: "/sheet/sheet_form_create.html/get_work",
// minLenght: 2,
// });
//}
function pop_other_fields() {
var url = "/sheet/sheet_form_create.html/get_work?workorder_id=" + $('#id_work_order').val();
var work_order = document.getElementById('id_work_order').value;
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
data: '',
success: function (data) {
if (data[0].success = "success") {
console.log(data[0].success);
$('#id_customer_name').val(data[0].customer_name);
$('#id_part_number').val(data[0].part_number);
$('#id_part_revision').val(data[0].part_rev);
$('#id_purchase_order').val(data[0].purch_order);
}
if (data.success = "workorder_not_found") {
alert("workorder not found :(")
}
}
});
}
});
the code here is never reached:
else:
x_json['success'] = 'workorder_not_found'
results.append(x_json)
because if if wo_data.exists(): is not true, then for x in wo_data: would never have any iterations in the first place.
Try:
def get_work(request):
if request.is_ajax():
q = request.GET.get('workorder_id', '')
wo_data = Dim_work_order.objects.filter(base_id__icontains = q )[:1]
results = []
if wo_data.exists():
for x in wo_data:
x_json = {}
x_json['success'] = 'success'
x_json['work_o'] = x.base_id
x_json['customer_name'] = x.name
x_json['part_number'] = x.part_id
x_json['part_rev'] = x.part_rev
x_json['purch_order'] = x.customer_po_ref
results.append(x_json)
else:
results.append({'success': 'workorder_not_found'})
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Categories

Resources