I am having a difficult time figuring out a javascript problem. I have script that I does an ajax call via a php script get data. This data is in this format "[12300000,13]"
when I do alert on data, I will exactly get that. I am interested in the values inside the bracket. So this is what I did:
var myObj = JSON.parse(data);
var temp = new Array();
temp=myObj.split(',');
when I try to do this;
alert(temp[0]);
I dont get anything back. Is there an easy way to do this in javascript. My whole script is below:
$.ajax({
url: 'get_data.php',
success: function(data) {
//when I do alert(data), I will get this format [123000000,45]//
var myObj = JSON.parse(data);
alert(myObj);//this will display this without the brackets123000000,45
//but when I do this
var temp = new Array();
temp=myObj.split(',');
alert(temp[0]); //does not return anything
},
cache: false
});
}
myObj is an array; JSON.parse will parse JSON into the corresponding Javascript objects.
You don't need to do anything
You already parsed the string into an array. Just get the first element:
> var arr = JSON.parse("[12300000,13]")
> arr[0]
12300000
Your problem here is actually alert(). Don't use it as a debugging tool. Use console.log() and open up your JS console, which will display objects in a friendly manner.
Related
So I am sending a list of objects from my ASP.NET MVC controller back to my ajax success response:
...
success: function (data) {
var predefinedData = data.serialize();
...
When I debug from browser, I see that the data parameter is reading as an array, which is ok, but the following error occurs:
Uncaught TypeError: data.serialize is not a function
I've read that I have to convert the "vanilla" parameter into jQuery so I did the following:
var makeJqueryArray = $.makeArray(data) //this passes ok
var predefinedData = $.param(makeJqueryArray).serialize(); //but then this reports the same error as before
Upon further inspection I see that $.makeArray(data) literally doesn't do anything since it stays exactly the same as before, an array with n number of elements.
Doing JSON.stringify(data); works however, but it is out of the question since that gives me a completely different format than what I need here.
So does anyone have any suggestions?
EDIT 1:
So here is the data I am receiving (as seen from the browser debugger watch):
data: Array[3]
0:Object
_int:false
avg:false
max:false
min:false
sensorID:5
sum:false
val:true
__proto__: Object
1:Object
2:Object
length:3
__proto__:Array[0]
And here is how i want to format it (the values don't match because I'm using different samples, but you get the point):
"SensorID=1&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=2&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=3&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=4&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=5&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=6&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=7&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=9&val=false&min=false&avg=false&max=false&sum=false&_int=false"
If you have an array and you want to make a request where the parameters are the key-value pairs of it, you can use simply $.param(yourArray);.
It will return a string ready to be used in your URL.
For example (taken from the jQuery.param page) :
var params = { width:1680, height:1050 };
var str = jQuery.param( params ); // str = "width=1680&height=1050"
This should the same in your case. So, try this :
var makeJqueryArray = $.makeArray(data) //this passes ok
var finalString = $.param(makeJqueryArray); // Should contain the string you want
This bit of code below scans an API on Wikipedia, and then is supposed to alert the title of it by getting the JSON property "title". However, it just alerts undefined, and for some reason, it alerts it twice. What am I doing wrong?
$.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Twitter', function(data){
for (var Object in data){
var Info = data[Object]
var Title = Info["title"]
alert(Title)
}
})
This will work:
$.get('https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Twitter', function(data) {
$.each(data.query.pages, function( index, value ) {
var title = value.title;
alert(title);
});
})
The query returns a data object, which has a query object within it, and one/multiple pages within that. Iterate over each page, and grab the title string.
JSFiddle
Note: You may want to learn to use your browser's debugging tools, and read up on the JSON format.
I'm having a slight issue here.
I'm trying to make a function that is supposed to send a HTTP request in Javascript which will then return data that I will be using on the website.
Anyways the issue I'm having here is that the parameters and values will not always be the same.
function getresults(values){
if(values != ''){
var exploded = values.split("&");
var getarr = exploded.split("=");
var array = new Array();
exploded.forEach(function(entry) {
var newexplode = entry.replace("=", ":");
array[newexplode[0]] = newexplode[1];
});
$.get(
"results.php",
{param : "value"},
function(data) {
alert(data);
}
);
}
};
So, what I need to do is to input all of the contents of the array into the the curlybrackets, where I've done an example of how params and values and sent.
getresults("search=general&searchterm=asd&wildcardend=no&wildcardbegin=no&page=1")
Here's an example of the call of an input.
The amount of parameters can vary and it'll be impossible to know how many I will have and so on.
I either need a new way of doing a HTTP request that is cross-browser compatible or I need some way of inputting this into the param:value curlybrackets.
Once again, read this carefully, I can't know how many params I will be recieving in beforehand as it may vary, and I will not be able to know in what order they are 100% either.
[EDIT] I made a dumb bypass which works, but I'm still interested if there are any alternate solutions.
Instead of constructing array you probably should be constructing a JSON Object
var paramObj = {};
for ( var entry in exploded){
paramObj[entry] = entry.split('=')[1];
}
$.get(
"results.php",
{param : paramObj},
function(data) {
alert(data);
}
);
"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there
I fetch a json object from the server and populate my view. I then change the data, push it back to the server. I then fetch a new copy of the data hoping it will refresh my view with any changes. However that doesn't happen. TIA
$(document).ready(function() {
var customer_id = get_customer_id();
var data = load_model();
contract_model = ko.mapping.fromJS(data,{});
ko.applyBindings(contract_model);
}
function load_model(){
var url = '/ar/contract_json?contract_id='+get_contract_id();
var data = '';
$.ajax({
type:'GET',
url:url,
async:false,
success: function(returningValue){
data = returningValue;
}
});
return data;
}
This initial load works fine. I then do some stuff and change one of the observables and push that data back to server. Server gets the update and then I do a new fetch of the data so that view will refresh (i know i can pass back the new data in one step but this in code i haven't refactored yet).
function refresh_data(contract_model){
var url = '/ar/contract_json?contract_id='+get_contract_id();
$.post(url,function(data){
console.log(data);
ko.mapping.fromJS(contract_model,{},data);
ko.applyBindings(contract_model);
console.log(ko.mapping.toJS(contract_model))
});
}
function refresh_data(contract_model){
var url = '/ar/contract_json?contract_id='+get_contract_id();
$.post(url,function(data){
console.log(data);
ko.mapping.fromJS(contract_model,{},data);
console.log(ko.mapping.toJS(contract_model))
});
}
function push_model(contract_model,refresh){
var url = '/ar/update_contract';
var data = {'contract':ko.mapping.toJSON(contract_model)}
delete data['lines'];
$.post(url,data,function(return_value){
if (refresh){
refresh_data(contract_model);
};
});
}
The console messages all show the new data coming back but my view never updates.
I believe the problem is with the order of parameters you pass into the ko.mapping.fromJS function when you are updating contract_model.
You have:
ko.mapping.fromJS(contract_model,{},data);
you want:
ko.mapping.fromJS(data, {}, contract_model);
#seth.miller's answer is correct. You can also leave out the middle "options" parameter if your contract_model is the same one that was mapped earlier. If there are only two arguments, ko.mapping.fromJS checks if the second argument has a "__ko_mapping__" property. If so, it treats it as a target, otherwise it treats it as an options object.
Based upon #DBueno's observation - for anyone using typescript I strongly recommend commenting out this method signature from your knockout.mapping.d.ts file.
// fromJS(jsObject: any, targetOrOptions: any): any;
Yes - just comment it out.
You'll then get a compile time error if you try to do :
ko.mapping.fromJS(item.data, item.target);
and you can replace it with the much safer
ko.mapping.fromJS(item.data, {}, item.target);
Safer because whether or not item.target has been previously mapped (and therfore would have a __ko_mapping__ property) it will always copy the properties.