I have a page where I want to add couple of controls
when I click on 1st control, I want my javascript to open particular JSONpage, gram the content and then output the content in specific <DIV id="one">. Then, when I select some of the elements in div id="one", I want The JavaScript to connect to another JSON page and get another array of data from there.
My question - how do I do the JSON part?
In other words, how do I get JavaScript version of:
$dataSet = json_decode(file_get_contents($url), true);
I am new to JavaScript and this thing takes so much time!!
Got this working
function getDates() {
jQuery(function($) {
$.ajax( {
url : "jsonPage.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var date = new Array();
var i = -1;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
if(x == 'date')
{
i = i + 1;
date[i] = y;
}
});
});
//output my dates; [0] in this case
$("#testArea").html(date[0]);
}
});
});
}
Related
I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have a javascript that sends some info to through an ajax request to the server and receives some data as Questions and their's ID's as a json array.
This is what the response json array i receive from the server looks like:
[
{
"ID":"1",
"question":"Write a function called addNum. "
},
{
"ID":"3",
"question":"Write a function called sumDouble "
}
]
And this is javascript:
$(document).ready(function(){
$("form#input_qnumber").submit(function() {
var questions = $('#questions').attr('value'); // written question
var quizname = $('#quizname').attr('value');
if (questions) { // values are not empty
$.ajax({
type: "POST",
url: "https://xxxx",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "application/json",
data: 'questions='+questions+'&quizname='+quizname,
success: function (data)
{
var JSONObject = JSON.parse(data);
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
console.log(JSONObject[key]["ID"] + ", " + JSONObject[key]["question"]);
}
}
}
});
}
else {
$('div#createquizresp').text("Enter question ID's separated by a comma to be included in the quiz");
$('div#createquizresp').addClass("error");
} // else
$('div#createquizresp').fadeIn();
return false;
});
});
As you see, I can parse the response json into a javascript object array, loop through it and dump the contents in console. What I would like though would be to create textarea element, give its id attribute the 'ID' key from my array and label it with the corresponding question key from the array. After this I can just append the element to a div inside my html. But I am not really sure how to do it or if its even possible. Please HALP.
if you want also a label element;
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
$('<label>')
.attr('for', JSONObject[key]["ID"])
.html(JSONObject[key]["question"])
.appendTo('wherever_you_want');
$('<textarea>')
.attr('id', JSONObject[key]["ID"])
.appendTo('wherever_you_want');
}
}
create dynamic elements input and label and then append these elements to the parent div or to the body what ever suits your requirement.
DEMO :https://jsfiddle.net/ew4mqhow/3/
<div id ="display"></div>
<script>
var textbox = document.createElement('input');
textbox.setAttribute("id", JSONObject[key]["ID"]);
var labell = document.createElement('label');
labell.setAttribute("for",JSONObject[key]["question"]);
labell.innerHTML = JSONObject[key]["question"];
document.getElementById('display').appendChild(textbox);
document.getElementById('display').appendChild(labell);
</script>
Answer by keune is perfect. One suggestion, tho - do add a prefix to foreign ID's. Just to be on safe side on case You'll assign ID's to other types of elements (ie. answers), too.
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
$('#quizquestions')
.append($('<label>')
.attr('for', 'Q' + JSONObject[key]["ID"])
.html(JSONObject[key]["question"]))
.append($('<textarea>')
.attr('id', 'Q' + JSONObject[key]["ID"]))
}
}
I have data in a table coming from multiple json api links.
my code currently is
<script src="js/1.js"></script>
<script src="js/2.js"></script>
Above this is a table code. Allowing the table to be sorted. It only has <th> and <thead> tags.
The issue as it stands looks like this:
I'm wanting ideally the price field to be sorted. below is the inside of the JS files
1.js
$.ajax({
type : 'GET',
crossDomain : true,
dataType : 'json',
url : 'api link here',
success : function (json) {
//var json = $.parseJSON(data);
for(var i=0; i<json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#tableid").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error : function(error){
console.log(error);
}
});
and here is the 2nd js file
$.ajax({
type : 'GET',
crossDomain : true,
dataType : 'json',
url : '2nd api',
success : function (json) {
//var json = $.parseJSON(data);
for(var i=0; i<json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tbody><tr><td>"+section+"</td><td>"+no+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#tableid").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
error : function(error){
console.log(error);
}
});
Now here is what i believe is the code to sort the js files in the table, Issue is I have no idea where to put it.
var sortTable = function(){
$("#tableid tbody tr").detach().sort(function(a,b){
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1))- parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
And
for(var i=0; i<json.results.length; i++) {
....
}
sortTable();
I would use a tablesorter jquery plugin but i would rather not.
Since you're pulling data from two ajax requests, perhaps it will be better to store both results in one global array that you can sort and loop through to build your table in price order.
var resultsArray = new Array();
for (var i = 0; i < json.results.length; i++) {
resultsArray.push(json.results[i]);
}
resultsArray.sort(function(a,b) {
return a.price - b.price;
});
for (var i = 0; i < json.results.length; i++) {
//print your table here
var price = resultsArray[i].price;
//etc...
}
I fully demonstrated this in a fiddle
is it possible for you to take both of the json reponses, sort them in order by price, and then add them to the dom? This way you don't have to access the dom so much just to sort your data?
This would go something like this, if you're using jQuery. Basically once both of your ajax requests resolve you can do whatever with the data you have. Fromt here you can merge them, sort them, and then run your piece to populate the table.
var urlDatas = [];
$.when(
$.getJSON(someUrl, function(data) {
urlDatas.push(data);
}),
$.getJSON(someOtherUrl, function(data) {
urlDatas.push(data);
})
).then(function() {
//not completely sure if extend returns a value or just mutates, target.
finalData = $.extend(true, {}, urlDatas[0], urlDatas[1]);
//run a sort on that data
sortData(finalData);
//add it to your dom
insertData(finalData);
});
A site that I'm using contains a JavaScript file, inside the file it contains a code with JSON and goes like this:
$.getJSON(API_URL + getSubdomain() + "/values");
The data file contains the code:
{"has_clicked_all":false,"has_clicked_already":false,"buttons":
[{"id":3922,"name":"button3992","has_clicked":false},
{"id":4613,"name":"button4613","has_clicked":false},
{"id":4339,"name":"button4339","has_clicked":false},
{"id":4340,"name":"button4340","has_clicked":false},
{"id":4341,"name":"button4341","has_clicked":false},
{"id":4622,"name":"button4622","has_clicked":false},
{"id":4623,"name":"button4623","has_clicked":false},
{"id":4828,"name":"button4828","has_clicked":false},
{"id":4829,"name":"button4829","has_clicked":false},
{"id":4861,"name":"button4861","has_clicked":false}]}
What I'm wanting to do is change all the value's to true without clicking on all of the buttons. I've tried doing a lot of research and spent 4 hours figuring out how I could do this and me being very new to all this just leaves me stuck...
I just need someone to give me a hand it would be greatly appreciated! Thankyou
Parse the json , modify the data , then re-encode to json
javascript:
var data = JSON.parse(json);
for(i = 0; i < data.buttons.length; i++){
data.buttons[i].has_clicked = true;
}
data.has_clicked_all = true;
data = JSON.stringify(data);
console.log(data);
demo
jQuery :
(function() {
$.getJSON(API_URL + getSubdomain() + "/values", function(data) {
data.has_clicked_all = true;
$.each( data.buttons, function( i, item) {
data.buttons[i].has_clicked = true;
});
data = JSON.stringify(data);
alert(data);
});
})();
Hi everyone i'm trying to display some random images while not loading (refresh) page
So how can i display random images on a page without refreshing the page ?
<script type="text/javascript">
$(function () {
$.ajax({
type: "get", url: "Home/Oku", data: {}, dataType: "json",
success: function (data) {
for (var i = 0; i < data.length; i++) {
var newFirmDiv= $(' <img src="../../banner_image/' + data[i] + '" width="154px" height="108px"/>');
$(".firmShowCase").append(newFirmDiv);
}
}
});
});
</script>
Here is my action method that provides return values an array
public ActionResult Oku()
{
var query = from table in db.news select table.news_image_name;
return Json(query, JsonRequestBehavior.AllowGet);
}
Here is result as you can see below
2nd Try:
function for min and max
(http://www.naden.de/blog/zufallszahlen-in-javascript-mit-mathrandom)
function getRandom(min, max) {
if(min > max) {
return -1;
}
if(min == max) {
return min;
}
var r;
do {
r = Math.random();
}
while(r == 1.0);
return min + parseInt(r * (max-min+1));
}
And Your Code
for (var i = 0; i < data.length; i++) {
randomIndex = getRandom(0, data.length-1);
var newFirmDiv= $(' <img src="../../banner_image/' + data[randomIndex] + '"width="154px" height="108px"/>');
$(".firmShowCase").append(newFirmDiv);
}
If you want to keep the random order...
...you have to save it like in a new array, afterwards you could save it via ajax in a database or a temp file. And the top of your current file you would have to check if there is an existing temp file; if it shall be bound to a user, you could generate a random key (like with time) save it in a session variable and name the tmp file or the data in the database with the same random key... so far my ideas, if it's that what you are looking for. Of cause it would be easier to do this on the server side right from the start.
First Answer:
(The question was not really clear - if something does not work and so on...)
First of all data is not returned as an array, but an object. But i think you do not understand the parameters of the ajax function very well.
In the url parameter should be the script (for example getImages.php) which shall be executed. So there you should collect the images, parse them to jason and print them, in that way it will be returned as data.
In the parameter data you can pass some params to the skript, which you can get by decoding them in php.
I just chose PHP for example.
If I am wrong and "Home/Oku" leads to some script you might show us what it does?