I am creating a Phonegap app which loads in information from vimeo using JSONp. I want to know if there is a way of creating a button that updates the feed either live or when a button is clicked. I have research all over for this answer but are yet to find an answer
I have be able to create a button that just runs the JSON request again, but this leads to there being duplicates of the JSON file in the DOM. So this leads me to my next question which is, is there a way to delete/remove an unwanted JSON file? This way I could add the new one and remove the old, hey presto JSON refreshed.
$('#jqt .info').click(function() {
refreshJSON();
});
function refreshJSON() {
//Vimeo .GET
$.ajax({
url: 'http://vimeo.com/api/v2/album/1751209/videos.json?callback=?',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data){
gotMeSomeJSON(data);
},
error: function(){
alert('Sorry unable to download data. You need a good wifi connection to run this app.');
}
});
In principle, to remove a js reference all you need to do is target it and use remove child, something like this for example:
var s = document.getElementsByTagName('script')[0]; //target the right one
s.parentNode.removeChild(s);
Related
I am a little new when it comes to JSON and Javascript , so please excuse me if if this is a stupid question, but I have run into a problem that is starting to drive me insane.
On a webpage I am including two scripts; jQuery and a file called "scripts2.js". In the same directory as scripts2.js, I have a JSON file; "settings.json". From within my "scripts2.js" file I am running he following code inside of a function.
var settingsPath = settings.json;
jQuery.getJSON(settingsPath, function (data){
jQuery.each(data, function(index){
console.log("!"+data[index].name);
/*unrelated other stuff */
});
});
Previously the settings.json file looked like this
[
{"name":"Standard Black"},
{"name":"Gold"},
{"name":"Silver"}
]
So naturally when I looked in the Chrome Dev Console the log would print out
!Standard Black
!Gold
!Silver
However, when testing what would happen upon editing my settings.json file I changed "name":"Gold" to "name":"Test".
[
{"name":"Standard Black"},
{"name":"Test"},
{"name":"Silver"}
]
After the json updates I tried refreshing the page but my console log is still printing out
!Standard Black
!Gold
!Silver
...
I am at a loss. I have no idea why the data being retrieved with jQuery.getJSON() is sending the data of my old settings.json even after the changes has been saved. I have perused my .php file (which is generating the HTML) , as well as my included javascript and there is no other mention of another json file or any sort of clone of my json file in any related directory.
I really have no idea what is going on and I am starting to go insane. Does anyone have an idea of what the issue might be?
I dont know if it matters but I am running a XAMPP stack on my localhost. All files (index.php, scripts2.js, and settings.json) are in a directory located inside XAMPP's htdocs folder.
EDIT: Thank you all for the speedy and thorough answers, many of you answered the question I was a bout to ask next. I really appreciate it!
This is because the browser is caching the file from your first request. Simply clear the cache and run it again and the new data will be retrieved.
UPDATE:
To prevent the browser from caching this file, change your AJAX settings like so:
jQuery.ajaxSetup({ cache: false });
Before you make the getJSON call
Try clearing web cache and restart local servers if you have not already
When using jQuery.ajax() instead of the shorthand method, you can disable caching like this:
jQuery.ajax(settingsPath, {cache: false})
jQuery will append a timestamp parameter to your request URL which changes with every request and therefore keeps the browser from caching the response.
To force the browser to get a new version each time you can use cache: false in jQuery.ajax()
$.ajax({
dataType: "json",
url: settingsPath,
cache: false,
success: function (data){
$.each(data, function(index){
console.log("!"+data[index].name);
});
}
});
Pass additional parameter to your requested url which value will change with every request.So,your browser will consider it as new request every time and will not cache the data.
var random = Math.round(new Date().getTime())
var settingsPath = 'settings.json&time=' + random;
jQuery.getJSON(settingsPath, function(data) {
});
});
You can use any algoritham that generate random new value everytime for random for every request.
OR
you can have same things with jQuery#Ajax method
jQuery.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So, set the optional parameter cache to false (this value by default is always true):
$.ajax({
dataType: "json",
url: url,
data: data,
cache: false, // If set to false, it will force requested pages not to be cached by the browser
success: success
});
Therefore, your getJson becomes:
var settingsPath = settings.json;
jQuery.ajax({
dataType: "json",
url: settingsPath,
data: data,
cache: false,
success: function(data) {
jQuery.each(data, function (index) {
console.log("!" + data[index].name);
/*unrelated other stuff */
});
}
});
I make a menu link with javascript. By using the parsing in php I display a menu with the help of javascript. The problem is how do I display data in accordance with the "id" which has been on the destination page.
Here's the code in index.html
function loadkategori(idnya){
$('#contentID').load('kategori.php?id='+idnya, function(){
$('#myListview').listview().listview('refresh');
});
}
$(document).ready(function(){
$.ajax({
url: 'http://localhost/fiqi/fiqi2/kuliner/www/parsing2.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
// $("#listview").append("<li><h2>"+item.namatempatnya+"<p>Kalimat</p></h2></li>");
// seharusnya menggunakan class, tidak inline function
$('#listview').append('<li data-filtertext="form checkboxradio widget checkbox input checkboxes controlgroups" onclick="loadkategori('+item.idkat+')">'+item.namakategori+'</li>');
});
// $("#listview");
// $('ul').listview('refresh');
$('#listview').listview().listview('refresh');
// $('#element').collapsibleset('refresh');
},
error: function(){
alert('Error terjadi');
}
});
});
here's the code in kategori.php
The code in kategori.php doesn't work on adobe phonegap.
I couldn't implement you code but as far as i understand, You need to use some http request function to get data from serverside php rather than using load(), go for using $.get(). That might work out as a solution to your problem.
function loadkategori(idnya){
var data = $.get('kategori.php?id='+idnya, function(data,status){
//PROCESS YOUR DATA OR CALL YOUR FUNCTION TO POPULATE YOUR LISTVIEW
});
}
Secondly you should use either xml or json data for client server communication. That would make your program simple and more efficient. You might paste your php code instead of putting screenshot so that some editing or testing can be done.
There is one feature on my site: delete without page refresh. The user just presses 'delete' and the browser will send Ajax-request. It will load 'delete' script with id parameter.
All work well. But it is not very good because of referential integrity of the database. For example, It is possible to delete street, where some people are living.
I want to upgrade my script. I want to add a check to delete script and don't let delete data if some 'people' are connected to 'street' table.
jQuery handler of button click:
$('body').on('click', '.deleteStreet', function()
{
var id = $(this).attr('id');
var hideMe = $(this).parent().parent();
var dataString = 'id=' + id;
if(confirm("Are you sure you want to delete street? It is possible some people living there!"))
{
$.ajax({
type: "GET",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
hideMe.hide();
}
});
return false;
}
});
It will call script anyway and now will delete data anyway. I can add some checks to delete script now and it wouldn't delete, but jquery script would work anyway and will hide table row anyway (because request was send ok, without 404, etc)
1) Is it possible to see delete script result and hide or not hide row depending on it? For example, it will return true or false, js script will catch it and show message about deleting or not deleting of data depending on it.
2) This problem caused by structure of my site. There are some switches on index.pl and load appropriate scripts loading depending on query (mode=street then load street.pl, mode=user then load users.pl etc). So it will show all data loaded before delete.pl script and it will be impossible to check script returned true or false.
Any help? :) Thank you!
P.S.: I am very sorry for my awful english.
You can have the result of your ajax call in the first parameter of the success callback. ex:
$.ajax({
type: "POST",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
if(e === '1'){
hideMe.hide();
}
}
});
try to log your result in the console for tests: console.log(e).
For deleting data you should use a POST request ( or DELETE but not supported by all browsers).
I dont know how your datas (streets) looks like but an other way could it be to return all your existing streets in a json object on the delete request result. And refresh all lines.
I have a bookmarklet which a user adds to their own browser bookmarks toolbar which collects images from a page they are looking at.
I want to log each time a user is clicking on any site and store the data in a mysql table. So i'm using an ajax call to post to a php file which processes the data sent to it.
However, this sometimes works and sometimes does not. Meaning, it works on some sites and not others.
What I'm trying is this:
(function()
{ // declare variables e.g. div.ids, div content etc then display it
......
//log the click
var dataString = '&url=' + encodeURIComponent(window.location.href) + '&page_title=' + encodeURIComponent(document.title);
$.ajax({
type: "POST", // form method
url: "http://myurl.com/includes/log_clicks.php",// destination
data: dataString,
cache: false
});
//END log the click
})();
When it doesn't work and i use Firebug to find out why, i sometimes get the error: TypeError: $ is undefined $.ajax({
Sometimes it still posts to the php file but with no data
Is there a better way to call ajax from within a js file on a user's browser?
As per suggestions, I've tried loading jquery by simply amending one of the variables like so:
div.innerHTML = '<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script><div class=....';
But that made no difference
You need jQuery present on the page in order to perform this. You will need to load jQuery if not present. A great approach is outlined here using the jQuerify code which actually just loads a portion of jQuery functionality that is needed.
I'm trying to lessen manual update work by using Yahoo Pipes and jQuery to update a table with upcoming events from a different domain. I have created this Pipe to gather the data, and it seems to work.
Now I am reading the JSON file with the following jQuery Script taken from this tutorial:
$.ajax({
type: "GET",
url: "http://pipes.yahoo.com/pipes/pipe.run?_id=57aa32bf3481c8dca0c07afcf9b9dc29&_render=json",
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
$('body').append(data.query.results.a.content);
}
});
The jQuery append failes, I guess because 'data.query.results.a.content' does not relate well to the JSON structure created by the pipe.
I've tried altering both the pipe and the append in several ways and am just short of giving up, I'd be very grateful for your Input.
Think you are parsing the json result incorrectly.
On viewing the json object here http://jsonviewer.stack.hu/
You will observe content node for each item is at value.items[0].a.content
i.e. try something like this :
$('body').append(data.value.items[0].a.content);
You will need to iterate the items array like this
$.each(data.value.items, function(index,element) {
$('body').append(element.a.content);
});
Try it on fiddle : http://jsfiddle.net/EFvJf/