I have a function that takes the values returned from an ajax call and adds a row to a table that is defined in the json values, but I don't think it is fetching the table correctly. Is there anything special I need to be doing? I know the data['table_name'] variable does have the correct value in it.
Here is the code I have.
function ajaxSuccess () {
var data = JSON.parse(this.responseText);
var elementObj = document.getElementById(data['table_name']);
var i = elementObj.size() + 1;
elementObj.append('<tr><td>Date</td><td>Name</td><td>' + data['new_comment'] + '</td></tr>');
i++;
return false;
}
This is not correct.
You have js variable var elementObj = document.getElementById(data['table_name']);
And you use jquery append().
Try var elementObj = $("#"+data['table_name']); instead.
Also check console for errors, you are probably receiving this:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'append'
p.s. you can also try this:
$(elementObj).append('<tr><td>Date</td><td>Name</td><td>' + data['new_comment'] + '</td></tr>');
without rewriting var elementObj to jquery variable.
Related
I want to display a name from this url http://api.open-notify.org/astros.json/
Here is my code,
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.results[0].formatted_name;
console.log('Name : ', name);
});
I want to display it with my h3 tag. I'm new to JSON and jQuery. I keep getting
index.html:631 Uncaught TypeError: Cannot read property '0' of undefined error
You have to use the success() or done() function.
var url = "http://api.open-notify.org/astros.json/";
$.getJSON(url).success(function (json) {
var name = json.people[0].name
console.log('Name : ', name)
})
If you are able to reach out to the specific endpoint and not be blocked by CORS it must be the format of the data.
Looking at the data, there is no property called results in your data. Try debugging that line to see the proper format of the variable json. It may be a string and you would need to call JSON.parse(json); in order to format it properly as an object.
You should be able to do:
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.people[0].name;
console.log('Name : ', name);
});
I have this code:
function parseContent(targetDiv) {
$("#"+targetDiv+" > [contentName]").each(function (index) {
var data = $(this).attr("contentData");
if(data != undefined) {
alert(data);
alert(jQuery.param(data));
}
})
}
It parses some html and looks for elements with contentName as an attribute in them. For each of those, check to see if there is an attribute contentData, and if so turn the json into parameters.
It's doing the each() just fine. However I get one alert (the first one) prints:
{reportId : 5}
which is correct, but then fails and in the console i get:
TypeError: this.replace is not a function
Im pretty sure that is correct JSON format. I have tried it with adding quotes also like {'reportId':5} but I get the same error;
Any Ideas?
It's because $.param expects a JSON Object as its parameter and not a string formatted as JSON. So if you pass something like this, it's going to fail:
var jsonElement = '{"reportId": 5}';
var result = $.param(jsonElement); //throws exception
Instead, if you do:
var jsonElement = '{"reportId": 5}';
var result = $.param(JSON.parse(jsonElement));
I'm using someresponse.getBody(); to store the XML response I'm getting back from a webservice. When I pass this to the below function, it's not able to be parsed corrected using search() or indexOf(). Both return a start and end pos of 10 and -1.
However, when I pulled the body of the response from the execution logs and hard coded the variable with that value. When I pass that value to the same function, it is processed as I expect.
This looks to be a format issue. Any idea what I can do here?
I'm restricted to just using Javascript or NetSuite API's and the code runs server side.
I call the function using: var xmlCCConnote = getValue('CCConnote', response);
function getValue(tag,xmlString){
var value;
var tempString;
var startTag,endTag;
var startPos,endPos;
startTag = "<"+tag+">";
endTag = "</"+tag+">";
tempString=xmlString;
startPos = tempString.indexOf(startTag) + startTag.length;
nlapiLogExecution('DEBUG', 'startPos = ', startPos);
endPos = tempString.indexOf(endTag);
nlapiLogExecution('DEBUG', 'endPos = ', endPos);
value = tempString.slice(startPos,endPos);
return value;
}
The xmlstring I was passing into the function was escaped. The following fixed the issue:
startTag = '<'+tag+'>';
endTag = '</'+tag+'>';
(i am new. please bear with me.) I have a jquery object that I need to convert back to html to use. What I am doing is using jQuery's get to get the HTML DOM of a local file. The data returned is then made into an object and I perform some tweaks on it (like changing hrefs etc.)
$.get(imagePath + "bloghome.aspx", function (data) {
var pageHtml = $(data);
pageHtml.find('a').each(function () {
var longHref = $(this).attr('href');
var tmp = longHref.lastIndexOf('ID=');
var id = longHref.substring(tmp + 3) + '.htm';
var newHref = imagePath.concat(id);
$(this).attr('href', newHref);
});
});
the object is created in the second line and then i change the hrefs. What I need now is to turn that object back into a string so that I can write it to a file.
I am using PhoneGap but any help would be appreciated as I am stumped
You can do this way using pageHtml[0].outerHTML:
$.get(imagePath + "bloghome.aspx", function (data) {
var pageHtml = $(data);
pageHtml.find('a').each(function () {
var longHref = $(this).attr('href');
var tmp = longHref.lastIndexOf('ID=');
var id = longHref.substring(tmp + 3) + '.htm';
var newHref = imagePath.concat(id);
$(this).attr('href', newHref);
var htmlString = pageHtml[0].outerHTML; //<-- Here
});
});
from http://api.jquery.com/html/
console.log(pageHtml.html());
Can you just do
pageHtml.html();
?
EDIT: Using this will only give you the contents inside the main wrapping element, if you want the entire thing, you can use:
pageHtml[0].outerHTML;
instead.
I've been sitting with this for hours now, and I cant understand why.
q is working. The URL does give me a proper JSON-response. It shows up as objects and arrays and whatnot under the JSON tab under the Net-tab in Firebug and all is fine. I've also tried with other URLs that i know work. Same thing happens.
I have another function elsewhere in my tiny app, wihch works fine, and is pretty much exactly the same thing, just another API and is called from elsewhere. Works fine, and the data variable is filled when it enters the getJSON-function. Here, data never gets filled with anything.
I've had breakpoints on every single line in Firebug, with no result. Nothing happens. It simply reaches the getJSON-line, and then skips to the debugger-statement after the function.
var usedTagCount = 10;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
for(var i = 0; i < usedTagCount; i++) {
tagString += query[i].key + ",";
}
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
debugger; /* It never gets here! */
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
debugger;
return flickrImageData;
}
Example of request URL (q):
http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=20&jsoncallback=?&tags=london,senior,iphone,royal,year,security,project,records,online,after,
I do wonder, since JSONView (the firefox plugin) cannot format it properly, that it isn't really JSON that is returned - the mime-type is text/html. Firebug, however, interprets it as JSON (as i stated above). And all the tag words come from another part of the app.
I think you might need to remove the
nojsoncallback=1
from your searchAPI string.
Flickr uses JSONP to enable cross domain calls. This method requires the JSON to be wrapped in a json callback, the nojsoncallback=1 parameter removes this wrapping.
EDIT: Apparently it works with nojsoncallback=1, I got this piece of code to work for me. What jQuery version are you using? JSONP is only available from 1.2 and up.
This works for me (slight modifications):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
var usedTagCount = 1;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
tagString = query;
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
}
search("cat");
</script>
When I try the url: http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=10&tags=mongo
it returns data, as it should -
try to change the getJSON to an $.ajax() and define a function jsonFlickrApi (data)
with the code you have in you callback function.
If that don't work - please post code to at jsbin.com <- so we can try it live - so much easier to debug.