I have written a code for getting data from another server through JSONP call (based on jQuery) please look at the code below....
$("#submit").click(function() {
var state=$("#state").val();
var city=$("#city").val();
$.ajax({
type: "GET",
url: "http://www.dizainstore.com/chrome/info.php",
async: true,
data: "state="+ state+ "&city="+ city,
dataType: 'jsonp',
success: function(response) {
var centres=response.centres_info.centre;
var address=response.centres_info.address;
var val ;
var val1 ;
var und
$.each(centres, function(i,cent){
val += "<div class='box2-l'>" + cent + "</div><div class='box2-r'>" + address[i] + "</div>" ;
});
var new_val = "<div class='box1'><div class='box1-l'>Center List</div><div class='box1-r'>Address List</div>"+val+"</div>"
$(".result1").html(new_val);
}
});
return false;
});
It's working fine for me. but When i used in Google Chrome Extension, it's not working, error occurred :- we can't use jquery Ajax call, they suggest xmlhttprequest. But i dont know how to convert this code into XMLhttpRequest. So please suggest me.
Thanks
Since the return is JSONP, it appears dizainstore is using a RESTful API and expects you to use JSONP with script injection:
http://en.wikipedia.org/wiki/JSONP#Script_element_injection
Your code would instead look something like this:
function handleDizain(response)
{
var centres=response.centres_info.centre;
var address=response.centres_info.address;
var val ;
var val1 ;
var und
$.each(centres, function(i,cent){
val += "<div class='box2-l'>" + cent + "</div><div class='box2-r'>" + address[i] + "</div>" ;
});
var new_val = "<div class='box1'><div class='box1-l'>Center List</div><div class='box1-r'>Address List</div>"+val+"</div>"
$(".result1").html(new_val);
}
$("#submit").click(function() {
var state=$("#state").val();
var city=$("#city").val();
//Create a new script tag
var loader = document.createElement( "script" );
loader.setAttribute( "type", "text/javascript" );
//Set the source
loader.src = "http://www.dizainstore.com/chrome/info.php?state=" + state + "&city=" + city + "&callback=handleDizain";
//Add it to the body
document.body.appendChild( loader );
});
If you want to make a cross-origin call in a Chrome extension, you don't have to use JSONP. You can simply use the Chrome extension cross-origin permissions: http://developer.chrome.com/extensions/xhr.html
Regards,
Udi
Related
Hi all and thanks in advance for the help:
i got this error:
Uncaught SyntaxError: Unexpected identifier
for line 65 (the line with the "Var query"... here the third line)
and when i click on the Execute button this is the other error:
Uncaught ReferenceError: retrieveData is not defined
(retrieveData is the function i call with the click)
i have used an existing code modifyng it for my purpose.
the very strange things are:
1: the original code run without errors (and it seems to me quite the same)
2: if i paste the url and the query and &output=json on the browser, it works fine... so i think it's not an error about mispelling...
this is the code I wrote:
<script type="text/javascript">
function retrieveData() {
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, "Firenze")}";
var url = 'http://it.dbpedia.org/sparql?default-graph-uri=&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['museum']['value'].replace("http://it.dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> () </h3></div>";
$('#output_div').append(html);
}
);
}
</script>
and this is the original code:
<script type="text/javascript">
function retrieveData() {
var query = "PREFIX : <http://dbpedia.org/resource/> PREFIX dbp: <http://dbpedia.org/ontology/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dbpprop: <http://dbpedia.org/property/> SELECT ?person ?b_date ?d_date ?abstract ?thumbnail WHERE { ?person rdf:type dbp:Person ; dbp:birthDate ?b_date ; dbp:deathDate ?d_date ; dbp:abstract ?abstract . OPTIONAL { ?person dbp:thumbnail ?thumbnail } FILTER ( ?b_date >= '1488-01-01'^^xsd:date && ?b_date < '1600-01-01'^^xsd:date && ?d_date < '1650-01-01'^^xsd:date ) FILTER ( langMatches(lang(?abstract), 'EN')) } ORDER BY ?person ?b_date";
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['person']['value'].replace("http://dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> (" + value['b_date']['value'] + " - " + value['d_date']['value'] + ")</h3></div>";
if (value['thumbnail'] != null)
html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
else
html += "<div class='inline thumb'><img src=''/></div>";
html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";
$('#output_div').append(html);
}
);
}
</script>
Thanks again
--UPDATE--
Obviously i 'm made a mess with quotation mark. Thanks dodl. Now it works.
A LITTLE NOTE if anyone tries to run this script:
It will come "XMLHttpRequest same domain policy error"...
Just add the '&callback=?' in the url, using the built-in support for JSONP in JQUERY.
You're not escaping your quotation marks properly, ie:
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, "Firenze")}";
should be
var query = "SELECT ?museum WHERE {?museum a <http://dbpedia.org/ontology/Museum>.?museum <http://dbpedia.org/ontology/address> ?address. FILTER contains(?address, \"Firenze\")}";
(Or alternatively, in javascript you can use single and double quotes to differentiate quotes within strings from string definition quotes.)
I have a problem. This code worked when the html was static and not appended, but when append data it does not...
I have appended data from a JSON-document like so:
$('#articles').append('<article><time pubdate="pubdate">' + pubDate + '</time><h2>' + headline + '</h2><p>' + bodyText + '</p></article>');
After this I create a variable containing the first article:
var currentElement = $("article:first");
Then I want to access currentElement.position():
console.log(currentElement.position());
But it comes back as undefined... It worked with unappended data? What am I doing wrong?
Thanks for the help!
EDIT: Here is the entire code:
$(document).ready(onDocumentReady);
function onDocumentReady()
{
console.log('Document ready');
$.ajax({
type:'GET',
url:'data.json',
dataType:'json',
success: jsonParser
});
function jsonParser(json)
{
$.getJSON('data.json',runData)
function runData(data)
{
$.each(data.article, writeData)
function writeData(keys,values)
{
var pubDate = values.pubDate;
var headline = values.headline;
var bodyText = values.bodyText;
$('#articles').append('<article><time pubdate="pubdate">' + pubDate + '</time><h2>' + headline + '</h2><p>' + bodyText + '</p></article>');
}
}
}
var currentElement = $("article:first");
console.log(currentElement.position());
EDIT AGAIN:
When I
console.log(currentElement);
I get:
[prevObject: x.fn.x.init[1], context: document, selector: "article:first", jquery: "1.10.2", constructor: function…]
context: document
length: 0
prevObject: x.fn.x.init[1]
selector: "article:first"
proto: Object[0]
Don't really understand that stuff, but thought it might help
UPDATE:
If I do a setTimeOut like this, I am able to access the element:
setTimeout(function()
{
var currentElement = $("article:first");
console.log(currentElement);
console.log(currentElement.position().left);
}, 1000);
It should be $("article:first-child")
Edit
Never mind :first works in jQuery.
Please make your ajax is returning data and article elements are getting created . If no elements are getting created then it will return undefined.
Before the success function, try to add: async: false in your ajax call.
$.ajax({
type:'GET',
url:'data.json',
dataType:'json',
async:false,
success: runData(data)
});
function runData(data){
$.each(data.article, writeData)
function writeData(keys,values){
var pubDate = values.pubDate;
var headline = values.headline;
var bodyText = values.bodyText;
$('#articles').append('<article><time pubdate="pubdate">' + pubDate + '</time><h2>' + headline + '</h2><p>' + bodyText + '</p></article>');
}
}
I am trying to get the title for a twitch.tv stream from an xml file using either jQuery or JavaScript and then post that title to a div (as a section header). The title is found in the <status> section of the xml file.
Below the code I currently have which doesn't seem to be working:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://www.twitch.tv/meta/koibu.xml",
dataType: "xml",
success: function(xml) {
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$(xml).find('meta status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
}
});
});
Here is a jsfiddle -with my broken script in- to play with.
Edit: solved it using a json call instead of reading xml
$(document).ready(function(){
var names = ["koibu"];
var obj = jQuery.parseJSON('{"name": {"life": "{life}","logo": "{logo}","status": "{status}","preview": "{preview}","url": "{url}"}}');
grabJSON();
function grabJSON() {
setTimeout(grabJSON,1000);
for (index = 0; index < names.length; ++index) {
$.getJSON("https://api.twitch.tv/kraken/channels/" + names[index] + "/?callback=?", function (json) {
$('#lefttitle').empty(),
$('#lefttitle').append("<h2>" + json.status + "</h2>");
});
}
}
});
This also allows me to set up a nice little array to grab more data from multiple channels if I want to extend it in future.
If you're not suffering from CORS, then the actual problem is below
$(xml).find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
xml variable represents the unparsed XML.
It has to like
$xml = $(xmlDoc);
$xml.find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
I managed to get your XML file, and the status tag contains Monday Mafia!
I'm working on a page that makes fairly heavy use of ajax. All the ajax forms appear to be working fine across browsers but one final step on the page is broken in IE8 and below.
Here is a demo page showing the problem: http://jolora.com/~fwm/
To reproduce the issue please fill in the final form (email name etc) - a list of markers will be shown on the map. The 'Request Appointment' button should fire an ajax function but instead it actually submits the form in IE7 and IE8 so it appears preventDefault isn't working.
Here's the relevant jQuery:
// Request appointment
$('#map').on('submit', 'form', function(event) {
event.preventDefault();
var solicitorID = $(this).attr('id');
solicitorRequest(solicitorID,applicationID);
});
function solicitorRequest(requestedSolicitor,currentApplication) {
$.ajax({
url: siteurl + 'wp-admin/admin-ajax.php',
data:{
'action':'do_ajax',
'fn':'request_solicitor',
'solicitor': requestedSolicitor,
'application': currentApplication
},
dataType: 'JSON',
success:function(data){
alert('Please check your email - this success function needs improving');
},
error: function(errorThrown){
alert('error');
//console.log(errorThrown);
}
});
}
The popups are built using Leaflet's bindPopup method http://leafletjs.com/reference.html#popup and here's the structure of the content I insert into the popup:
var popupContentBegin = '<form id="'
+ solicitor.id + '">'
+ '<h3>' + solicitor.name + '</h3>'
+ '<div class="contact-details">'
+ '<span class="addr">' + solicitor.address + '</span>';
var popupContentTel = '';
if(solicitor.telephone != false) {
popupContentTel = '<span class="tel">'
+ solicitor.telephone
+ '</span>';
}
var popupContentEnd = '</div>'
+ '<button type="submit">Request appointment</button>'
+ '</form>';
var popupContent = popupContentBegin + popupContentTel + popupContentEnd;
var marker = L.marker([lat, lng], {icon: solicitorIcon}).bindPopup(popupContent, popupOptions);
Any help would be greatly appreciated! Thanks.
Try changing your selector to:
$(document).on('submit', '#map form', function(event) {...
http://api.jquery.com/live/
EDIT: You need to call this function inside a ready function so that you can be sure the DOM was completely loaded:
$(function () {
// Put code here
});
I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}