I'm trying to output html using an ajax request from a jsonp file . When using console.log I'm seeing the data looping fine, however when using a variable to grab the loop and output in html, I'm only seeing one result. What am I missing?
$.ajax({
url: "http://sitedotcom/blog/json",
dataType: "jsonp",
jsonpCallback: "jsonpCallback",
success: jsonpCallback
});
function jsonpCallback(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key]["title"] + ", " + data[key]["entry_id"]);
rssData = '<h2>' + data[key]["title"] + "</h2><p>" + data[key]["blog_summary"] + "</p>";
}
$('#blog-content').html(rssData);
}
}
You have $('#blog-content').html(rssData); inside the loop....so only the last result will show since html() replaces all content.
Try using append() instead or concatenate rssData each iteration and set html() after loop completes
It looks like rssData is out of scope when you are adding it to your #blog-content. Also you are outputting different data when doing your console log and setting your rssData variable.
If you could provide the json layout and also the html layout you are trying to append to.
Related
I have made a HTML site that reads a .json with javascript/jQuery and writes to it with PHP.
I then have a c++ backend that writes and reads to the same .json.
I want to be able to send what button is selected by the players to the c++.
The .json that javascript reads isn't always the .json that I have modified with PHP or C++.
It won't always have the updated data, the time to get the updated data can be instant, a few seconds or e few minutes.
I have tried to remove caching and I have checked that the file gets updated
To load the .json on the website I use:
var $JSONList = $('#JSONList');
$.getJSON("json/playerMode.json", function(json) {
console.log(json); // this will show the info it in firebug console
var stringed = JSON.stringify(json);
var response = JSON.parse(stringed);
console.log(response); // this will show the info it in firebug console
$.each(response, function(i, itt){
$JSONList.append( "</br>" + itt.Name + " has pressed: " + itt.Button + " :(())");
})
});
This is called by a <button>
Since this sometimes won't load the updated .json, is there some way that I can force javascript to load the local .json again?
First, let's make the assumption this url works - except the caching issue and address that and other things as noted.
Change from the shortcut "json/playerMode.json" to $ajax
Force to NOT cache the results
Added a fail just in case
fixed syntax for "<br />"
removed unneeded code as the JSON would be parsed already as long as it is valid. IF it is not valid JSON and it only returns "a string, that looks like JSON", you should use dataType: "text json" to force jQuery conversion/parse
or consider using a converter (see below)
MIGHT need header('Content-Type: application/json') for PHP
if you are NOT returning a true JSON string, use a converter to make it into one, see Using Converters here: https://api.jquery.com/jQuery.ajax/
This from https://api.jquery.com/jquery.ajax/
Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET
parameters.
$.ajax({
type: "GET",
url: "json/playerMode.json",
cache: false,
data: "",
dataType: "json" // force automatic parse of the JSON string returned
}).done(function(json) {
console.log(json); // this will show the info it in firebug console
// should not need
// var stringed = JSON.stringify(json);
// not needed, see above
// var response = JSON.parse(json);
//console.log(response); // this will show the info it in firebug console
//$JSONList - what is this? it should be in here somewhere...so I did that
let $JSONList = $('#JSONList');
// should be parsed already, so changed to that
$.each(json, function(i, itt) {
$JSONList.append("<br />" + itt.Name + " has pressed: " + itt.Button + " :(())");
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="JSONList"></div>
I'm pretty much a complete beginner at javascript and jQuery, so please bear with me.
I have a Spark-API running, and a web front-end that uses it through ajax calls.
I'm trying to call this function
function getSpotifyURL(ms, name) {
$.ajax({
url: "http://localhost:8081/playlist?ms=" + ms + "&name=" + name,
dataType: "json",
})
.done(function( data ) {
console.log(data);
})
}
The method is placed outside of:
$(document).ready(function() {
The reason it's outside is that I get an error upon calling it saying it's "undefined" if it's within $(document).ready.
The Spark-method is supposed to return a String (and it does when you try it directly through the browser).
The way I'm calling the getSpotifyURL-method is through a html button's "onclick". Like this:
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
The problem:
The .done-block does nothing in my code. Nothing is printed to console.
What I've tried:
Using "success" within the ajax part instead of .done
Placing the function with $(document).ready(function() { ... }
I understand that you might need more information to be able to help me, but I'm not sure what else information to provide right now. So if there's something you need to know, just ask.
Ideas?
SOLVED!
I'm a dumb person and forgot to remove dataType: "json", as the Spark-server in this instance returned a String, not a json object. Anyway, thanks for your input everybody. Much appreciated.
I think the problem is when you bind your function onclick. There is a syntax error, as you can see on the browser console
function getSpotifyURL(ms, name) {
console.log("http://localhost:8081/playlist?ms=" + ms + "&name=" + name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
I guess data is a variable, so you should call it without brackets
<a href='#' onclick='getSpotifyURL(data[i].duration, data[i].destination)'>Create Spotify playlist for this trip</a>
The reason you are getting undefined method when you are placing the function inside the $(document).ready(function() { ... }); call is because you are using the onclick attribute to call the function. $(document).ready(...) is not in global context as to where you onclick attribute is, and would therefore not recognize it from within the document.ready resulting in your undefined method error.
When sending your Ajax request, you also need to specify a type of request (GET or POST) that you are making. I would also suggest restructuring your ajax call to look more like #Moe's answer.
If you want to get it inside the DOM, consider doing the following:
HTML
<!-- I gave the link a class name and removed the onclick= attribute -->
Create Spotify playlist for this trip
JavaScript
$(document).ready(function() {
// I gave the <a> link a click handler
$(".create-spotify-playist").on("click", function(e) {
e.preventDefault(); // prevents link from requesting
var ms = ?? //I'm not sure where you're getting your parameters from,
var name = ?? //so you will probably have to figure out how to get those in here yourself
$.ajax({
type: "GET",
url: "http://localhost:8081/playlist",
data: { ms: ms, name: name },
success: function(data) {
console.log("Success: " + data);
},
error: function(data) {
console.log("Error: " + data);
}
});
});
});
I gave the link a click handler and placed it inside the $(document).ready, and by removing the onclick attribute from earlier, it can now be triggered from inside $(document).ready.
At the moment I have multiple forms, and am writing the JavaScript out very simply. I want to create a simple comment system using the following AJAX, but am running into troubles that I cannot sort out..
The AJAX call looks like this:
var dataString = 'commentauthor=' + commentauthor + '&parentid=' + parentid +'&linkid='+
linkid + '&comment=' + comment + '&location=' + location;
alert("check : " + dataString)
$.ajax({
type: "POST",
url: "comments/addcomment.php",
datatype: "html",
data: dataString,
success: function(){
alert('comment added!');
},
error: function(){
alert('failed adding comment!' +dataString);
}
The dataString at all times pulls out the correct information from the forms. Also, the PHP the AJAX is sending it to already works when it's set as the forms action, and all the $_POST[''] names match up.
I've been looking around but can't figure it out. Am I encoding the data wrong or something? The PHP side of things doesn't even get to the AJAX response, so it's got to be just failing to send right?
Also, is there a better way to check JavaScript errors? I've been using the google chrome console but half the time when something goes wrong it doesn't through up an error anyway (like this time)
Is addcomment.php printing anything out? I vaguely remember having a similar problem which was because the PHP file wasn't returning anything. If it isn't, try this before the end of the file:
echo 1;
so i have a website made in ASP.NET that uses JS to generate some DOM elements after getting settings from the users account.
problem is that after i sign out and log in with a different user name i get the generated elements from the previous user and i don't know why. the code that generates the elements is as follows:
$.ajax({
url: '#Url.Content("~")' + 'Ticket/GetTvrtke',
async: false,
success: function (data) {
document.getElementById("header_tvrtka_holder").innerHTML = data;
}
});
and a little afterward its is used as such:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
$.each(tvrtke, function (index, value) {
$("#KlijentMultiSelect").append("<option value=\"" + value + "\" id=\"" + index + "\" >" + value + "</option>");
});
now when i log off and sign in as a different user the ajax code above doesn't trigger the getTvrtke URL that gets the settings wich generate the elements and i don't know why.
Ajax by default caches the response of the calls. YOu can set it to false so that there is a fresh request every single time by using the below at the top of your application.
$.ajaxSetup({cache: false});
I'm getting an ajax output success data.
Where the data contains some html text and a script.
But the script is not executing, how can I execute the script.
Let's say Ajax response obj is
<div>something....</div><script>alert("test");</script>
the above code is my Ajax response.The div is getting rendered, but the alert is not working.
Assuming you are not using JSON or jQuery, or any other library, and your AJAX call returns some HTML and/or javascript which is being added to your existing document (eg. using innerHTML), any javascript returned using AJAX will not execute in the browser - except for events on elements in the HTML.
So if your AJAX call returns <input type="button" value="Click me" onclick="alert('hello');" />, the js alert will work ok, but if your AJAX call returns <script type="text/javascript">alert('hello');</script> it will not execute. In that case, you would have to parse the result to extract the javascript and execute it, using a function such as this:
function extract_and_execute_js(output_to_parse)
{
if(output_to_parse != '')
{
var script = "";
output_to_parse = output_to_parse.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){if (output_to_parse !== null) script += arguments[1] + '\n';return '';});
if(script)
{
if (window.execScript)
{
window.execScript(script);
}
else
{
window.setTimeout(script, 0);
}
}
}
}
If you are retrieving the JSON formatted result from AJAX call, you can just use eval to execute the javascript.
Assume, if the result json is formed like this
var res = '{"Data": "<something>",
"script": "alert(something)"}';
var out = eval("(" + res + ")");
var data = out.data;
eval(out.script);
Interestingly enough, I use jQuery and using the html() function was enough to get the JavaScript to execute. So more or less I had nothing special to do.
There is a simplified version:
var myform = $('form#form-id');
$.post(myform.attr('action'), myform.serialize(), function(response) {
$('#some-id').html(response.message);
}
In my case the code kicked in automatically so I did not need any other of the solutions proposed here.
Not sure if you are using a library, but with Prototype I had to set
evalScripts: true
before JavaScript would be eval-ed. See here for more info:
http://www.sergiopereira.com/articles/prototype.js.html#UsingAjaxRequest
Using jQuery here is a simple bit of code:
$.ajax({
type: "POST",
url: "getData.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result);
}
});
But, to actually use the results of the variable result I ended up using a javascript library, from http://www.json.org/js.html, I did:
success: function(result) {
var myData = JSON.parse(result.d);
There are probably better approaches, but this was simple, and worked for me, so I just use this. Later, when the project is in production I may go back and clean this up, but that is after I get everything working.