I've written the following code to get JSON data with a POST request.
$.post("http://example.com/songs/search_api/index.php",
"data[Song][keyword]=Stereophonics",
function(data){
/*$("#results").append(data);*/
alert("test");
var songdata = JSON.parse(data);
//$("#results").empty();
var i = 0;
for (i=0;i<=songdata.total;i++)
{
//alert(i);
var songhtml = "<ul><li><img src=\"" + songdata.data[i].artwork + "\" /></li><li>" + songdata.data[i].title + "</li><li>" + songdata.data[i].artist + "</li><li>" + songdata.data[i].length + "</li><li>" + songdata.data[i].listen + "</li></ul>";
//alert(songhtml);
$("#results").append(songhtml);
}
//var objectasstring = concatObject(songdata);
//alert(objectasstring + "\n\n" + songdata);
}
);
The problem is as soon as I put in a function (this works without the above code) the function fails to run;
function postRequest() {
alert("hello??");
}
This is for mobile Safari on the iPhone.
Thanks in advance.
Solved! My problem? The form. I was using a form so the page was being refreshed when the function was run.
Related
In the following lines of code, I try to add a function inside html tag in javascript:
nuevo = "<p class='item'>" + res.tarea + "<button onclick = '" + return EliminarTareas(database) + (" + res.tarea +");'>" + "Eliminar" + "</button></p>";
$('#listatareas').append(nuevo);
function EliminarTareas(id, base) {
base.transaction(function(tx) {
tx.executeSql("DELETE tarea FROM Tareas WHERE tarea=?", [id], function () {
});
});
}
The main problem is this part +return EliminarTareas(" + database + ", " + res.tarea +");'>". It discards the second parameter since you closed the paranthesis ), and it also has quote problems.
It should be like this +" return EliminarTareas(" + database + ", " + res.tarea + ");'>"
However, I believe addressing this task with .data would be effective, and it may provide a better structure. Below is my version with some codes from yours (DEMO: https://jsfiddle.net/9q4hLs3a/):
var nuevo = $("<p class='item'><button data-var1='" + database + "' data-var2='" + res.tarea + "'>Eliminar</button></p>");
$('#listatareas').append(nuevo);
$(document).ready(function(){
$(document).on('click', '#listatareas button', function(){
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
EliminarTareas(var1 , var2 )
});
function EliminarTareas(id, base){
base.transaction(function(tx){
tx.executeSql("DELETE tarea FROM Tareas WHERE tarea=?", [id], function (){
});
}
I think this is what you wanted
"<p class='item'>"+ res.tarea +"<button onclick = 'EliminarTareas("+database+","+res.tarea +")'>Eliminar</button></p>";
EDIT: It's telling me that my li is an illegal token. Still not sure what to do about this as I thought I was appending inside a ul
So I have to fetch a JSON array of some public Github repos and append the title, link, description, and basic information from the first 10 commits of each repo to the page. I already have the title, link and description working, but I'm lost when it comes to bringing in the commits. They're located at a different address than the initial information, so I made a second ajax request inside my first one to the commits address, but nothing is working. It may just be a syntax error or something as I've found from extensive searching that it is possible to nest ajax requests.
Here's my code, chopped up into each separate function (I've replaced the org name with 'name' for anonymity's sake):
main function:
function main() {
$.ajax({
type: 'GET',
url: 'https://api.github.com/orgs/name/repos',
error: function(xhr, status, error){
//var err = eval("(" + xhr.responseText + ")");
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
complete: function(data){
display_content(data);
}
});
}
main();
content display function:
function display_content(_data){
for (var i = 0; i < _data.responseJSON.length; i++) {
$("#listing").append(
"<h2>" +
"" + _data.responseJSON[i].full_name + "</h2>" +
"<p>" + _data.responseJSON[i].description +
"<h3>Latest Commits</h3>" +
"<ul id= \"" + _data.responseJSON[i].name + "commits\">"
);
commits(_data.responseJSON[i].name);
$('#listing').append(
"</ul>" +
"</p>" +
"<br/>"
);
}
}
commit information function:
function commits(repo){
$('#listing').find('h3').text("Latest Commits to user/" + repo);
return $.ajax({
type: 'GET',
url: 'https://api.github.com/repos/user/' + repo + '/commits',
error: function(xhr, status, error){
//var err = eval("(" + xhr.responseText + ")");
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
complete: function(commit_data){
for(var i = 0; i < 10; i++){
$('#listing').append(
"<li>
<div>
<img src=\"" + commit_data.responseJSON[i].author.avatar_url + "\">
<a href=\"https://github.com/" + commit_data.responseJSON[i].author.login + "\">
<b>" + commit_data.responseJSON[i].author.login + "</b>
</a>
<b>" + ($.timeago(commit_data.responseJSON[i].commit.committer.date)) + "</b><br />
<i>SHA: " + commit_data.responseJSON[i].sha + "</i>
</div>
<a href=\"https://github.com/user/" + repo + "/commit/" + commit_data.responseJSON[i].sha +
"\" target=\"_blank\">" + commit_data.responseJSON[i].commit.message +
"</a>
</li>"
);
}
}
});
}
I know it's a lot of code, I apologize in advance. I know the problem lies somewhere in the last two functions but I wanted to include everything to be sure.
If anyone has any experience with grabbing and parsing Git repo info I would really appreciate any advice on this. I'm willing to scrap everything and start over if need be to make this work, but I would like to avoid using any libraries aside from jQuery.
Thank you to anyone who helps! I appreciate it.
It's telling me that my li is an illegal token. Still not sure what to do about this as I thought I was appending inside a ul
You are using multi-line string literal for adding html. The line breaks need to be escaped, and this can be done via a backslash.
Change to
function commits(repo){
$('#listing').find('h3').text("Latest Commits to user/" + repo);
return $.ajax({
type: 'GET',
url: 'https://api.github.com/repos/user/' + repo + '/commits',
error: function(xhr, status, error){
//var err = eval("(" + xhr.responseText + ")");
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
complete: function(commit_data){
for(var i = 0; i < 10; i++){
$('#listing').append(
"<li>"+
"<div>"+
"<img src=\"" + commit_data.responseJSON[i].author.avatar_url + "\">"+
"<a href=\"https://github.com/" + commit_data.responseJSON[i].author.login + "\">"+
"<b>" + commit_data.responseJSON[i].author.login + "</b>"+
"</a>"+
"<b>" + ($.timeago(commit_data.responseJSON[i].commit.committer.date)) + "</b><br />"+
"<i>SHA: " + commit_data.responseJSON[i].sha + "</i>"+
"</div>"+
"<a href=\"https://github.com/user/" + repo + "/commit/" + commit_data.responseJSON[i].sha +
"\" target=\"_blank\">" + commit_data.responseJSON[i].commit.message +
"</a>"+
"</li>"
);
}
}
});
}
after Oyeme's advise, i have changed my code, but still cannot work. it can alert "testing" but cannot alert DBuser_name .
By the following coding, i can create a content like the image below. My problem is that, if the user click one of the people in the list, i would like to extract the student.data.user_name into localStorage. however, in my coding below, seems that i did wrong?
function getStudentList() {
$.getJSON('http://mydomain.com/getStudents.php?jsoncallback=?', function(data) {
$('#studentList li').remove();
$('#load').hide();
//students = data.user_name;
$.each(data, function(index, student) {
//$('#studentList').append('<li><a href="tutor_student_detail.html?user_name=' + student.data.user_name + '">' +
$('#studentList').append('<li><a href="tutor_student_detail.html">' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</a></li>');
$("li a").click(function() {
window.localStorage["view"] = $(this).data('user_name');
});
});
$('#studentList').listview('refresh');
});
}
Below are the coding of tutor_student_detail.html (js part)
function start(){
var localUsername=window.localStorage.getItem("view");
$.getJSON('http://mydomain.com/getStudent.php?user_name='+localUsername+'&jsoncallback=?', displayStudent);
alert("testing");
}
function displayStudent(data) {
var DBuser_name=data[0].data.user_name;
alert(DBuser_name);
var employee = data.item;
$('#username').text(student.data.user_name);
$('#pw').text(student.data.password);
$('#id').text(student.data.id);
$('#actionList').listview('refresh');
}
the output of json string is something like
?([{"data":{"id":"4","user_name":"studentB","book":"4567","role":"Student"}}]);
$('#studentList').append('<li><a href="tutor_student_detail.html"
data-name="'+student.data.user_name+'">' +
'<h4>' + student.data.user_name + '</h4>' +
'<p>' + student.data.role + '</p>' +
'</a></li>');
$("li a").click(function() {
window.localStorage["view"] = $(this).data('name');
});
I'm using the following function to create a list of links from a JSON-File and put them into a span element (jquery has been initialized)
$(document).ready(function() {
function createjson(category) {
var content = "";
i = 0;
$.getJSON(category + ".txt", function(data){
while(data[i] != null) {
content = content + '<li class="liste"><a target="_blank" class="liste" href="' + data[i].url + '">' + data[i].name + '</a></li>';
i++;
}
});
document.getElementById("list_" + category).innerHTML = content;
}
createjson("cat1");
});
However, if I use it like this, the span element remains empty. It is only when I replace
document.getElementById("list_" + category).innerHTML = content;
with
alert("test");
document.getElementById("list_" + category).innerHTML = content;
that I get the desired output. How can I get it without printing out an alert message beforehand?
That is becuase .getJSON() is an asynchronous method. Your code will try to update the DOM with content, before the server had time to respond to the request. Therefor no content is inserted.
With the alert, you stop the execution long enough for the server to respond, therefor it works when you add the alert.
The correct way to do it would be to move your content update into the success-callback instead, which is always run after the server has responded:
$.getJSON(category + ".txt", function(data){
while(data[i] != null) {
content = content + '<li class="liste"><a target="_blank" class="liste" href="' + data[i].url + '">' + data[i].name + '</a></li>';
i++;
}
$("#list_" + category).html(content);
});
I replaced your document.getElementById("list_" + category).innerHTML = content; with the somewhat shorter jQuery equivalent $("#list_" + category).html(content); in the above example as well.
It's not the alert which is fixing this, the alert is basically blocking the UI for long enough for the AJAX request to complete.
$.getJSON is an asyncronous method. This means that the result of the function call is not always available immediately, you'll need to move your code which sets the list element HTML inside the $.getJSON callback:
$.getJSON(category + ".txt", function (data) {
while(data[i] != null) { ... }
document.getElementById("list_" + category).innerHTML = content;
});
Put the html append in callback, also reset the i when call back starts.
$(document).ready(function() {
function createjson(category) {
$.getJSON(category + ".txt", function(data)
{
var content = "";
for(i=0; i<data.length; i++)
{
content = content + '<li class="liste"><a target="_blank" class="liste" href="' + data[i].url + '">' + data[i].name + '</a></li>';
}
document.getElementById("list_" + category).innerHTML = content;
});
}
createjson("cat1");
});
Use this !== to compare with not equal to NULL
while(data[i] !== null) {
content = content + '<li class="liste"><a target="_blank" class="liste" href="' + data[i].url + '">' + data[i].name + '</a></li>';
i++;
}
I have a few cascading dropdowns on the bottom of my php page. Each time a user selects an option from the dropdown the following function is called to add the value of that option to my url variables. Currently the page refreshes to the top each time which is a huge problem. Normally I would use something like onCLick="window.location='page.htm#bottom';" to refresh to the bottom of the page but the below function stops working when I add the #bottom. Can someone help me adjust this function or give me other ideas that will refresh to the bottom of the page when the function is done.
function reload5(form){
if(document.getElementById('fda1').checked) {
var fda = '1';
}else if(document.getElementById('fda0').checked) {
var fda = '0';
}
var val=form.category.options[form.category.options.selectedIndex].value;
var val2=form.subcat.options[form.subcat.options.selectedIndex].value;
var val3=form.subcat1.options[form.subcat1.options.selectedIndex].value;
var val4=form.subcat2.options[form.subcat2.options.selectedIndex].value;
var comp1=form.mname.options[form.mname.options.selectedIndex].text;
var itemnum=document.getElementById('item').value;
var desc=document.getElementById('desc').value;
var quan=document.getElementById('quan').value;
var list=document.getElementById('list').value;
var uom=form.uom.options[form.uom.options.selectedIndex].text;
self.location='add_products.php#bottom?fda=' + fda + '&desc=' + desc + '&quan=' + quan + '&list=' + list + '&uom=' + uom + '&item=' + itemnum + '&cat=' + val + '&cat2=' + val2 + '&cat3=' + val3 + '&cat4=' + val4 + '&comp=' + comp1 ;
}
So this doesn't work: self.location='add_products.php#bottom?fda=' + fda
But this does : self.location='add_products.php?fda=' + fda
Any idea where to put the #bottom?
The issue is that the hash must come after the query string at the end. See this article. Try this... (I also cleaned up the code)
function reload5(form){
var val=form.category.options[form.category.options.selectedIndex].value,
val2=form.subcat.options[form.subcat.options.selectedIndex].value,
val3=form.subcat1.options[form.subcat1.options.selectedIndex].value,
val4=form.subcat2.options[form.subcat2.options.selectedIndex].value,
comp1=form.mname.options[form.mname.options.selectedIndex].text,
itemnum=document.getElementById('item').value,
desc=document.getElementById('desc').value,
quan=document.getElementById('quan').value,
list=document.getElementById('list').value,
uom=form.uom.options[form.uom.options.selectedIndex].text,
fda;
if(document.getElementById('fda1').checked) {
fda = 1;
} else if(document.getElementById('fda0').checked) {
fda = 0;
} else {
fda = -1;
}
window.self.location.href = 'add_products.php?fda=' + fda + '&desc=' + desc + '&quan=' + quan + '&list=' + list + '&uom=' + uom + '&item=' + itemnum + '&cat=' + val + '&cat2=' + val2 + '&cat3=' + val3 + '&cat4=' + val4 + '&comp=' + comp1 + "#bottom";
}
What I don't understand is why you are not doing something with Ajax that would not cause the page to refresh at all.