Format of OnClick link in a .append - javascript

I am building a iPhone PhoneGap app, I am trying to include a Share button to share some data I pull from the server using JSON.
Here is what my code looks like:
$.ajax({
url: 'http://www.myurl.com.au/api/get_category_posts/?category_id=5&custom_fields=displaynative&callback=?',
dataType: 'json',
data: null,
// crossDomain: true,
beforeSend : function() {$.mobile.loading('show')},
complete : function() {$.mobile.loading('hide')},
timeout: 15000,
success: function(data, status)
{
(data.portfolio);
$.each(data.posts, function(i,item){
if(item.title_plain != undefined){
if(item.custom_fields.displaynative != undefined){
$('#datanews').append("<div data-role='collapsible' class='ui-nodisc-icon ui-alt-icon' data-theme='a' data-icon='r'><h4>" + item.title_plain + "</h4><p>"+ item.custom_fields.displaynative +"</p><a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + ")'>Save/Share</a></div>").trigger('create');
}
}
});
IT works except the Save/Share button and I know why but i don't know how to fix it.
Needs to be: `Save/Share
But I can't use the "" for the on click because it causes a formatting error.
Anyone know what I can do?
Thanks,
Ben

Your last parenthesis was on the wrong side.
Your code
<a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + ")'>Save/Share</a>
Fixed
<a href='#' class='ui-btn' onclick=window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + "')>Save/Share</a>
Could also recommend to put double quotes on the onclick attribute:
<a href='#' class='ui-btn' onclick=\"window.plugins.socialsharing.share('" + item.title_plain + "', null, null, '" + item.url + "'\")>Save/Share</a>

Related

Ajax MySQL POST responses with Object without data

I am using that code to send a POST request to add data to a mysql table.
var todoItem = $(this).serialize();
$.ajax({
type: "POST",
url: "/test",
data: todoItem,
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
if(data.success){
$('#todo-list').append(
'<li class="list-group-item">' +
'<span class="lead">' +
data.todo +
'</span>' +
'<div class="pull-right">' +
'Edit' +
'<form style="display: inline" method="POST" action="/test/${data.id}">' +
'<button type="submit" class="btn btn-sm btn-danger">Delete</button>' +
'</form>' +
'</div>' +
'<div class="clearfix"></div>' +
'</li>'
);
} else {
$("#todo-list").append(
'<li class="list-group-item">' +
'<span class="lead">' +
'Fail' +
'</span>' +
'<div class="clearfix"></div>' +
'</li>'
);
}
}
Then i want to use data from the response to append to my list.
But if(data.success) isnt passing. why is that?
Also my data in console.log looks like object Object and doesnt contain the inserted row data.
Do i need to send a get request now to retrieve the last data row?

Update: How do I dynamically populate a list with data from a JSON file?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?
JSON file
[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]
jQuery
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});
$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});
HTML
<li id="test_ID"></li>
I do receive a couple of errors. The Line:
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
gives the following error: invalid number of arguments and unclosed String literal.
I am also unsure of how to identify to specific elements in the JSON file.
Update
I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!
You have a couple of errors in your javascript. See the corrected version below:
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
$("#test_ID").empty(); //emtpy the UL before starting
// **************** correction made to the line below ***********************
$.each(result, function(i, v, d) {
// **************** correction made to the line below ***********************
$("#test_ID").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>'); // correction made here
});
}
});
});
I did a quick fiddle. I don't quite understand what you're doing with v.test being unmarked inside the HTML tags so I did not include it. I used minimal JQuery to avoid complexity.
https://jsfiddle.net/ndx5da97/
for (record in data) {
$("#test_ID").append('<li id="' + data[record].id + '">' + data[record].testDate + '</li>');
}
Hope this helps!

JQuery .append list items not triggering a script when clicked on

I am working on a page that loads data from an XML file that populates an HTML unordered list. An unordered list is used to make the gallery from the tutorial on this page. Unfortunately, the created thumbnails do not trigger the javascript which creates the expanding preview.
The javascript should be activated when the user clicks on an anchor in the unordered list.
Any suggestions as to how to resolve this issue would be great.
Code
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$('#load').fadeOut();
$(xml).find("painting").each(function () {
$("ul#og-grid").append('<li> <a href="http://google.com/" data-largesrc="images/' + $(this).find("image").text() + '" data-title="' + $(this).find("title").text() + '" ' + '<>' + '<img src="images/thumbs/' + $(this).find("image").text() + '" alt="img01"/> </a> <li> ');
$(".painting").fadeIn(1000);
});
}
</script>
You need to attach the click event. You can do this whilst populating your li or after. I would do the following
$(xml).find("painting").each(function () {
$('<li> <a href="http://google.com/" data-largesrc="images/' + $(this).find("image").text() + '" data-title="' + $(this).find("title").text() + '" ' + '<>' + '<img src="images/thumbs/' + $(this).find("image").text() + '" alt="img01"/> </a> <li> ')
.click(yourClickFunction)
.appendTo('ul#og-grid');
$(".painting").fadeIn(1000);
});
Don't forget to change yourClickFunction.
Hope that helps
use this line for click event
$(document).on('click', 'element-selector', function () {
// Do Stuff Here
});
You can use following JS code for this
$(document).on('click', 'ul#og-grid li', function () {
// Do Stuff Here
});

URL Name not resolved in Jquery

I am trying to dynamically build up HTML using JQuery in ASP.NET MVC5. I have so far had success, but the URL cannot be resolved in the JQuery Code.
My code looks something like this:
$.ajax({
type: 'POST',
url: '#Url.Action("QuerySearch")',
dataType: 'json',
data: {
queryName: $("#queryText").val()
},
success: function (data) {
// var items = '';
$.each(data, function (i, item) {
var resource_Url = item.ResourceURL;
// var resource_url = item.ResourceURL;
var append_data = $('<div class="row">'
+ '<h3>' + item.ResourceTitle + '</h3>'
+ '</div>'
+ '<div class="row">'
+ '<span class="label label-primary" style="margin:3px;font-size:small;">'
+ item.ResourceEducation
+ '</span>'
+ '<span class="label label-warning" style="margin:3px;font-size:small;">'
+ item.ResourceGrades
+ '</span>'
+ '<span class="label label-info" style="margin:3px;font-size:small;">'
+ item.ResourceSubject
+ '</span>'
+ '<a href="#Url.Content("' + item.ResourceURL + '")">'
+ '<img src="#Url.Content("~/Content/Resources/download_icon.png")" alt="Download Resource" style="height:24px;width:24px;"/>'
+ '</a>'
Although this code is able to retrieve the image for the download_icon defined in my project, it is not able to display / embed the URL fetched from the server by my function which I am trying to display in the <a href> tag.
Any help is greatly appreciated.
You will need to pass the complete url value from the server as a property of the data received. Or have it stored locally
ASP code doesn't run in the browser, only on server
The trick was simple, the href tag had to be changed to:
'<a href="' + item.ResourceURL + '">'
It worked like a charm

JQuery Form Submission with enter key AJAX API

I've tried various solutions, but none are suitable for my particular case!
How can I make it so that when the user presses 'Enter' the form submits & searches.
I also want to try and remove the JavaScript from the HTML document, and move it to the ajax.js document & select it.
I'm unsure of the correct syntax to do so.
I am using rotten tomatoes API with AJAX by the way.
search.php
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="button" id="button" value="Go!" onClick="filmlist(this.form)">
</form>
ajax.js
function filmlist (form) {
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = form.inputbox.value; //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
}
}
$("form").submit(function(){
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
return false;
});
or you can just return false at the end of your filmlist function.
You can detect an enter keypress in the #inputbox element with the following jQuery code:
$('#inputbox').keyup(function(e)
{
if(e.keyCode == 13)
{
//do your stuff
}
});
You can also use $('#inputbox').change() to directly load movies when the user is typing.
Do not forget that some old or mobile browser do not have JavaScript support. Always build an server side solution as fallback.

Categories

Resources