Trouble reading from json file in Javascript - javascript

I know next to nothing about ajax and json. Right now I'm trying to read the data from dealerData.json into my MVVM viewModel and 'data' keeps coming back as undefined.
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
success: function (data) {
obj = JSON.parse(data);
}
});
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
});

Try like this:
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
})
.done(function (data) {
obj = JSON.parse(data);
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
});
})

ko.applyBindings(DealerNumberLotNumberViewModel(obj)); - this should go inside the callback method though like this -
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
success: function (data) {
obj = JSON.parse(data);
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
}
});
Because obj is undefined till the callback method "success" actually assigns it something. and ko.applyBinding method should execute once obj is defined. Hence, it should go inside the callback method.
Also, it is a good idea to always have a failure callback method, just so that any failure doesn't go uncaught.
$(function () {
var obj;
$.ajax({
dataType: "json",
url: "/Scripts/dealerData.json",
success: function (data) {
obj = JSON.parse(data);
ko.applyBindings(DealerNumberLotNumberViewModel(obj));
},
error: function(args) {
console.log('error occured: '+ args);
}
});
Hope, this helps

Related

Display error on ajax response from php function

I have some ajax call like this
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
alert(data);
},
});
}
And php function like this
function export_database(){
return $response;
}
The problem is in that response I have something like this
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3fa58ee1-48bf0cb9f60bfa25."
}
I want to alert only title, but when i try data.title , i got undefine
Do I must encode or decode something, thanks?
This is what you need. Just access the object by data.title and it will show in the alert()
You need to define dataType as json in your request.
If its does not work then use JSON.parse(data) like this:
var response = JSON.parse(data)
alert(response.title)
Try below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: 'json'
data: data,
beforeSend: function () {},
success: function (data) {
alert(data.title);
},
error: function(error){
//Error
alert(error.title)
}
});
}
Hope this helps.
Try Below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var parsedData = jQuery.parseJSON(data)
alert(parsedData.title);
},
});
}
You have to use JSON.parse() for accessing data objects Like this:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var res = JSON.parse(data)
alert(res.title);
},
});
}

ajax success response change as #html.raw

I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this
It was the dataType in your ajax request. It should be json:
dataType: "json"

Revealing module pattern method echo undefined

I wrote this function as revealing module pattern, but when I call the get method in console by metadataModule.get(); it echoes undefined in console.
var metadataModule = function () {
var metadataurl = 'http://farskids326.com/data.json';
function getMetadata() {
console.log("Metadata Function Called")
$.ajax({
url: metadataurl,
dataType: "json",
success: function (data) {
console.log(data);
}
});
}
return {
get: getMetadata,
};
}();
Where did I made a mistake in this code?
When you are working in the console, the return value of the last expresion is echoed after any command. The method you are using doesn't have an explicit return value. So, that may be why you see undefined.
This probably means that your ajax call is encountering an error. Try changing it to log when either success or error happens, like so:
$.ajax({
url: metadataurl ,
dataType: "json",
success: function(data){
console.log('called success!');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('called error!');
}
});
Then, when you run your code, you should see exactly which callback is being executed. Hopefully, that will give you a good starting point for debugging the issue.
The getMetadata function returns nothing so yes, it will output undefined. for it to respond with the content of the JSON you need to make the ajax call synchronous and return the value you get.
var metadataModule = function () {
var metadataurl = 'http://farskids326.com/data.json';
function getMetadata() {
console.log("Metadata Function Called")
var content = {}
$.ajax({
url: metadataurl,
async : false,
dataType: "json",
success: function (data) {
content = data;
}
});
return content
}
return {
get: getMetadata,
};
}();

How to check ajax return value

I have an ajax call and it retunrs some value. Now i need to check the value in javascript. How can i do it
$('#cm').blur(function () {
var cmnumber = document.forms['myform']['cm'].value;
$.ajax({
type: 'get',
url: "/validatecm/" + cmnumber,
cache: false,
asyn: false,
data: cmnumber,
success: function (data) {
alert(data)
},
error: function (data) {
alert(data)
}
})
});
Now i need to access the "data" in my javascript submitformfunction. Any help wil be appreciated
success: function(data) {
console.log(data);
useInAnotherFunction(data);
}
function useInAnotherFunction(data)
{
...use here
}
If you use console.log(data); you can view clearly data what you have
You are already accessing the data here
alert(data)
If you still want to access it outside your success callback then make it like this
success: function(data) {
YourFunctionCall(data)
}

javascript undefined

Why cant I access the render function when ajax returns successfully? maybe im going crazy but i've done this before.
Its telling me that this.render is not a function?
DataItem.prototype = {
display: function () {
$('body').append(this.name + ": " + this.getData(this.rootData, this.subData) + "<br />");
},
getData: function (rootData, subData) {
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
success: function (json){
this.render(json);
}
});
},
render: function (json) {
var res = [];
for(var i=0, t; t=json.log.entries[i]; i++) {
var p = t.request.url;
if (p!=undefined) res.push(p);
}
return res.length;
}
};
The scope has changed when you try to call this.render(). I believe this contains the ajax request object instead of the DataItem object.
A simple solution is doing like this:
getData: function (rootData, subData) {
var self = this;
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
success: function (json){
self.render(json);
}
});
},
Edit: I was wrong, inside the success function the this variable contains the options for the ajax request, however my solution is still correct. See more in the jQuery documentation (http://docs.jquery.com/Ajax/jQuery.ajax#options)
Just to add to #adamse answer. If you want to externalize your success function instead of using an anonymous function you could use the following to pass additional parameters:
function handleSuccess(json) {
this.self.render(json);
}
$(function() {
$.ajax({
type: "GET",
url: "json/data.js",
data: "",
dataType: "json",
// pass an additional parameter to the success callback
self: this,
success: handleSuccess
});
});
since the following code works (i.e "abcd" is printed), I am not sure what is the problem you are facing unless you would share more code.
<script>
DataItem = function(){};
DataItem.prototype = {
display: function () {
return 'a';
},
getData: function () {
document.write(this.render());
return this;
},
render: function () { return "abcd"; }
};
di = new DataItem();
di.getData();
</script>

Categories

Resources