Challenge:
While on URL1(random wikipedia page), make an ajax request to URL2(100 most common words wikipedia page), format a list out of the returned data to be used later.
I have to run this from the console while on "URL1"
example:
Navigate to URL1
Open Console
paste code
hit enter
So far I have been able to grab the entire html source while on URL1 with the following:
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function (response) {
console.log(response); // works as expected (returns all html)
}
});
I can see in the console the entire HTML source -- I then went to URL2 to figure out how to grab and format what I needed, which I was able to do with:
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
Now this is where my issue is -- combining the two
$.ajax({
url:'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type:'GET',
dataType:'html',
success: function(data){
// returns correct table data from URL2 while on URL2 -- issue while running from URL1
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
};
});
Im guessing this is due to the HTML I want to map is now a string, and my array is looking for HTML elements on the current page which it of course would not find.
Thanks
Simple fix here! You're exactly right, it's not parsing the html you return, so just tell jQuery to convert it into an object it can use $(data) and use that to find what you need.
In essence, your 'document' now becomes $(data) which you will use as the source of all your queries.
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function(data) {
var myVar = data;
Names = $.map($(myVar).find('.wikitable tr'), function(el, index) {
return $(el).find('td:last').text()
});
console.log(Names);
}
});
Related
I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});
I'm using an $.ajax(); request to make a call to my controller. Inside the console.log();, it's correctly displaying all of the data coming in but when I try to display it on the browser via $('#displayCoins').text(item.oldCoins); - only the very last piece of data if being displayed instead of all of the data.
What am I doing wrong and how can I go about rectifying this in terms of displaying all of the data on the browser?
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
$('#displayCoins').text(item.oldCoins);
});
}
});
The problem that you are having is you are REPLACING the text every time through the loop instead of appending it.
One solution is to append the data to an array, then output it to the DOM via a single join.
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
oldCoins = [];
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
oldCoins.push(item.oldCoins);
});
$('#displayCoins').text(oldCoins.join("\n"));
}
});
var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/
I am attempting to create a glossary tooltip for a website that finds keywords from a json file that is being created by sitecore. I need to get the "Text:" parts from the json file and make then a variable in my jquery so they are the keywords that are found and wrapped with the appropriate tags. I had it working to the point where i could get console to log that there were 2 entries in my json file but that's it.
Here is my sample json code:
[{"Id":"ef339eaa-78e1-4f9e-911e- 096a1920f0b6","Name":"Glossary","DisplayName":"Glossary","TemplateId":"b27d2588-3d02-4f5f-8064-2ee3b7b8eb39","TemplateName":"Glossary","Url":"/Global-Content/Glossary/Glossary","Version":1,"Created":"\/Date(1343987220000)\/","CreatedBy":"sitecore\\rgoodman","Revision":"ae8b3ae0-d0ca-4c4a-9f27-a542a31ab233","Updated":"\/Date(1348137810133)\/","UpdatedBy":"sitecore\\admin","Text":"Glossary","Content":"A bit of test content for the glossary"},{"Id":"3fa51ad4-cfb6-4ff1-a9b5-5276914b2c23","Name":"Abraham","DisplayName":"Abraham","TemplateId":"b27d2588-3d02-4f5f-8064-2ee3b7b8eb39","TemplateName":"Glossary","Url":"/Global-Content/Glossary/A/Abraham","Version":1,"Created":"\/Date(1348148640000)\/","CreatedBy":"sitecore\\admin","Revision":"231284ec-9fb9-4502-ad79-a5806479ecba","Updated":"\/Date(1348148779656)\/","UpdatedBy":"sitecore\\admin","Text":"Abraham","Content":"This is a lincoln person"}]
But I suppose this is not of any use as it is just the "Text:" part i am looking to return.
Here is my jquery:
function getData(url) {
var data;
$.ajax({
async: false,
url: '/_assets/js/glossary.json',
dataType: 'json',
success: function(data.Text){
data.Text = response;
}
return(response);
});
}
function HighlightKeywords(keywords)
{
var el = $("body");
$(keywords).each(function()
{
var pattern = new RegExp("(" +this+ ")", ["gi"]);
var rs = "<mark href='#' class='tooltip'>$1</mark>";
el.html(el.html().replace(pattern, rs));
});
}
HighlightKeywords(data.Text);
Essentially i need to return the "Text:" bit of json where data is on the HighlightKerywords function. Where am i going wrong?
Any help would be much appreciated. Thanks
Your function is not syntactically formatted properly. Your return must go inside of the success function in the synchronous example, and not randomly placed in the ajax object..
function getData() {
$.ajax({
async: false,
url: '/_assets/js/glossary.json',
dataType: 'json',
success: function(data){
//HighlightKeywords(data.Text);
//or
return(data.Text);
}
});
}
Ajax is Asynchronous communication, you can't insert its response into a global variable and expect to be able to work with it.
You need to do all the work on the data.text in the success function.
success: function(response){
HighlightKeywords(response.Text);
}
I'm trying to send JSON data to my web server via jQuery and I'm running into an error.
Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}
code I am testing:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.
UPDATE
code I got to work
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.
You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/
Also, the JSON.stringify call is not necessary, jQuery will take care of that for you.
var obj = {
'id':45,
'isRead':true
};
$.ajax({
url: "/notification/read",
data: obj,
success: function(data, textStatus){
/* code here */
}
});
$.ajax(url, obj);
You need to send an object as second param
{success: success, data: data}
Documentation is here:
http://api.jquery.com/jQuery.ajax/
You have to pass parameters as one object, not multiple ones