i want to use ajax variable in other function - json

I want to use modal, so i get the data value from ajax.
the data is like that [{'source_name': '인터넷', 'description': '여행자료', 'source_slug': '_1', 'subject_name': '여행', 'subject_slug': '_6'}]
I want to put the value of source_name "인터넷" to source_name variable.
I want to use soure_name variable at this line.
html += '<li><span> 출처 : ' + source_name + ''
but source_name is undefined.
please help me
this is code.
function showModal(){
var pk = $(this).find('img').attr('id');
$.ajax({
url : '/photo/' + pk + '/',
async: false,
success: function(data){
data= JSON.stringify(data)
var source_slug = data[0]["source_slug"];
var source_name = data[0]["source_name"];
var description = data[0]["description"];
var subject_slug = data[0]["subject_slug"];
var subject_name = data[0]["subject_name"];
}
});
var src = $(this).find('img').attr('src');
var largeImg = $(this).find('img').attr('data-bsp-large-src');
if(typeof largeImg === 'string'){
src = largeImg;
}
var index = $(this).attr('data-bsp-li-index');
var ulIndex = $(this).parent('ul').attr('data-bsp-ul-index');
var ulId = $(this).parent('ul').attr('data-bsp-ul-id');
var theImg = $(this).find('img');
var pText = $(this).find('.text').html();
var modalText = typeof pText !== 'undefined' ? pText : 'undefined';
var alt = typeof theImg.attr('alt') == 'string' ? theImg.attr('alt') : null;
clicked.img = src;
clicked.prevImg = parseInt(index) - parseInt(1);
clicked.nextImg = parseInt(index) + parseInt(1);
clicked.ulIndex = ulIndex;
clicked.ulId = ulId;
$('#bsPhotoGalleryModal').modal();
var html = '';
var img = '<img src="' + clicked.img + '" class="img-responsive"/>';
html += img;
html += '<span class="' + settings.iconClose + ' bsp-close"></span>';
html += '<div class="bsp-text-container">';
html += '<li><span> 출처 : ' + source_name + ''
html += '</span></li>'
html += '<li><span> 과목 및 단원 :' + subject_name + ''
html += '<li><span>' + description + '</span></li>'
html += '</div>';
html += '<a class="bsp-controls next" data-bsp-id="'+clicked.ulId+'" href="'+ (clicked.nextImg) + '"><span class="' + settings.iconRight + '"></span></a>';
html += '<a class="bsp-controls previous" data-bsp-id="'+clicked.ulId+'" href="' + (clicked.prevImg) + '"><span class="' + settings.iconLeft + '"></span></a>';
$('#bsPhotoGalleryModal .modal-body').html(html);
$('.bsp-close').on('click', closeModal);
showHideControls();
}

You need to make the change inside success not after:
function showModal(){
var pk = $(this).find('img').attr('id');
$.ajax({
url : '/photo/' + pk + '/',
async: false,
success: function(data){
data= JSON.stringify(data)
var source_slug = data[0]["source_slug"];
var source_name = data[0]["source_name"];
var description = data[0]["description"];
var subject_slug = data[0]["subject_slug"];
var subject_name = data[0]["subject_name"];
var src = $(this).find('img').attr('src');
var largeImg = $(this).find('img').attr('data-bsp-large-src');
if(typeof largeImg === 'string'){
src = largeImg;
}
var index = $(this).attr('data-bsp-li-index');
var ulIndex = $(this).parent('ul').attr('data-bsp-ul-index');
var ulId = $(this).parent('ul').attr('data-bsp-ul-id');
var theImg = $(this).find('img');
var pText = $(this).find('.text').html();
var modalText = typeof pText !== 'undefined' ? pText : 'undefined';
var alt = typeof theImg.attr('alt') == 'string' ? theImg.attr('alt') : null;
clicked.img = src;
clicked.prevImg = parseInt(index) - parseInt(1);
clicked.nextImg = parseInt(index) + parseInt(1);
clicked.ulIndex = ulIndex;
clicked.ulId = ulId;
$('#bsPhotoGalleryModal').modal();
var html = '';
var img = '<img src="' + clicked.img + '" class="img-responsive"/>';
html += img;
html += '<span class="' + settings.iconClose + ' bsp-close"></span>';
html += '<div class="bsp-text-container">';
html += '<li><span> 출처 : ' + source_name + ''
html += '</span></li>'
html += '<li><span> 과목 및 단원 :' + subject_name + ''
html += '<li><span>' + description + '</span></li>'
html += '</div>';
html += '<a class="bsp-controls next" data-bsp-id="'+clicked.ulId+'" href="'+ (clicked.nextImg) + '"><span class="' + settings.iconRight + '"></span></a>';
html += '<a class="bsp-controls previous" data-bsp-id="'+clicked.ulId+'" href="' + (clicked.prevImg) + '"><span class="' + settings.iconLeft + '"></span></a>';
$('#bsPhotoGalleryModal .modal-body').html(html);
$('.bsp-close').on('click', closeModal);
showHideControls();
}
});}

Related

How to insert line break (enter) in Whatsapp message sent via jQuery

This is how I am sending whatsapp message via jQuery
var ques = "I";
var a = "am";
var b = "having";
var c = "a good";
var d = "time";
$(document).on("click", '.whatsapp', function() {
var whatsappMessage = ques + "\r\n\r\n" + a + "\r\n" + b + "\r\n" + c + "\r\n" + d;
var whatsapp_url = "whatsapp://send?text=" + whatsappMessage;
window.location.href = whatsapp_url;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showques" style="margin-left: 10px;font-size: 32px;">
</div>
<div style="width:300px;padding: 20px;background-color:#5755d9;">
<a class="whatsapp" style="font-size: 40px;color:white; text-decoration: none;">Whatsapp</a>
</div>
output = I \r\n\r\n am \r\n\r\n having \r\n\r\n a good \r\n\r\n time
I want an output like this:
I
am
having
a good
time
Add the following line in the code and it will work
whatsappMessage = window.encodeURIComponent(whatsappMessage);
$(document).on("click", '.whatsapp', function() {
var whatsappMessage = ques + "\r\n\r\n" + a + "\r\n" + b + "\r\n" + c + "\r\n" + d;
if( isMobile.any() ) {
whatsappMessage = window.encodeURIComponent(whatsappMessage);
var whatsapp_url = "whatsapp://send?text=" + whatsappMessage;
window.location.href = whatsapp_url;
} else {
alert("Please share this in mobile device");
}
});

Slick Slider not initializing with API json

Trying to incorporate slick slider with an API but for some reason it won't work.
Not sure if I'm doing something wrong.
html
<div class="row">
<div id="test">
<div class="card top">Hello! My name is<div class="name">Izzy</div><div class="location">Alamo, CA</div><div class="sex-age">Female, adult</div></div>
<div class="card top">Hello! My name is<div class="name">Izzy</div><div class="location">Alamo, CA</div><div class="sex-age">Female, adult</div></div>
<div class="card top">Hello! My name is<div class="name">Izzy</div><div class="location">Alamo, CA</div><div class="sex-age">Female, adult</div></div>
</div>
</div>
<div class="row">
<div id="cats">
</div>
</div>
You can see the first slider "#test" does work with the same html markup as the one in the bottom named "#cats"
For some reason the slider #cats won't initialize though. Does it have to do with me using append() to the div with id "cats"?
js
$(document).ready( function() {
$.getJSON("https://api.myjson.com/bins/187677", function(data){
$.each(data.pets, function() {
var name = this["pet_name"];
var sex = this["sex"];
var age = this["age"];
var state = this["addr_state_code"];
var image = this ["large_results_photo_url"];
var city = this ["addr_city"];
if ( sex = "m") {
sex = "Male";
}
if ( sex = "f") {
sex = "Female";
}
$("#cats").append(
"<div class='card top'>" +
"Hello! My name is"+
"<div class='name'>" + name + "</div>" +
"<div class='location'>" + city + ", " +state + "</div>" +
"<div class='sex-age'>" + sex + ", " + age + "</div>" +
"</div>"
);
});
});
$('#cats').slick();
$('#test').slick();
});
THank you in advanced!
You need to initialize the slick plugin for the #cats after you have inserted the relevant slides in the DOM
$(document).ready(function() {
$.getJSON("https://api.myjson.com/bins/187677", function(data) {
$.each(data.pets, function() {
var name = this["pet_name"];
var sex = this["sex"];
var age = this["age"];
var state = this["addr_state_code"];
var image = this["large_results_photo_url"];
var city = this["addr_city"];
if (sex = "m") {
sex = "Male";
}
if (sex = "f") {
sex = "Female";
}
$("#cats").append(
"<div class='card top'>" +
"Hello! My name is" +
"<div class='name'>" + name + "</div>" +
"<div class='location'>" + city + ", " + state + "</div>" +
"<div class='sex-age'>" + sex + ", " + age + "</div>" +
"</div>"
);
});
$('#cats').slick();
});
$('#test').slick();
});
Alternatively you can initialize the plugin earlier, and use the .slice('slickAdd', 'html node here') method
$(document).ready(function() {
$('#test').slick();
$('#cats').slick();
$.getJSON("https://api.myjson.com/bins/187677", function(data) {
$.each(data.pets, function() {
var name = this["pet_name"];
var sex = this["sex"];
var age = this["age"];
var state = this["addr_state_code"];
var image = this["large_results_photo_url"];
var city = this["addr_city"];
if (sex = "m") {
sex = "Male";
}
if (sex = "f") {
sex = "Female";
}
$("#cats").slick('slickAdd',
"<div class='card top'>" +
"Hello! My name is" +
"<div class='name'>" + name + "</div>" +
"<div class='location'>" + city + ", " + state + "</div>" +
"<div class='sex-age'>" + sex + ", " + age + "</div>" +
"</div>"
);
});
});
});

jquery div undefined with .html()

I am using Jquery ajax.
I have made ajax call to fetch data and concact the html string and attached to id of div.
$("#divMenuList").html(JsMenuListHtml);
alert($("#divMenuList").html());
But with alert is showing undefined. I have it using listing if i am page change it showing first time with html string but if i will delete second page record and re-call that function it will showing undefined.
Here is the whole function:
function performlisting(data, JsCurrPage) {
var JsMenuTitle = '';
var JsOrderNumber = '';
var JsMenuId = '';
var JsMenuListHtml = '';
var JsCounter = 0;
var JsAlternateRow = '';
var JsIsActive = "false";
var JsIsActiveClass = "";
var JsIsActiveTitle = "";
if (data.Data.length > 0) {
for (i = 0; i < data.Data.length ; i++) {
JsCounter++;
if (JsCounter % 2 == 0) {
JsAlternateRow = "alternate-row";
}
else {
JsAlternateRow = '';
}
//set true/false for update status
if (data.Data[i]['IsActive'] == true) {
JsIsActive = "false";
JsIsActiveClass = "icon-3 info-tooltip";
JsIsActiveTitle = "Published";
}
else if (data.Data[i]['IsActive'] == false) {
JsIsActive = "true";
JsIsActiveClass = "icon-4 info-tooltip";
JsIsActiveTitle = "UnPublished";
}
else {
JsIsActive = "false";
JsIsActiveClass = "icon-4 info-tooltip";
JsIsActiveTitle = "UnPublished";
}
JsMenuTitle = data.Data[i]['MenuTitle'];
JsOrderNumber = data.Data[i]['OrderNumber'];
JsMenuId = data.Data[i]['MenuId'];
JsMenuListHtml = JsMenuListHtml +
'<tr class= ' + JsAlternateRow + '>' +
'<td style="width:3.4%;"><input type="checkbox" value=' + JsMenuId + ' /></td><td style="width:38.8%;">' + JsMenuTitle + '</td>' +
'<td style="width:39%;">' +
'<a title="Up-Rank" href="javascript:void(0);" onclick="return performUpMenu(\'' + JsOrderNumber + '\', \'' + JsMenuId + '\')"><img src=' + JsUpImage + '></a>' +
'<a title="Down-Rank" href="javascript:void(0);" onclick="return performDownMenu(\'' + JsOrderNumber + '\', \'' + JsMenuId + '\')"><img src=' + JsDownImage + '></a>' +
'' + JsOrderNumber + '</td>' +
'<td class="options-width">' +
'' +
'<a href="javascript:void(0);" onclick="return performstatusmenu(\'' + JsIsActive + '\', \'' + JsMenuId + '\');" title= ' + JsIsActiveTitle + ' class=' + JsIsActiveClass + '></a>' +
'</td>' +
'</tr>';
}
$("#divMenuList").html("");
$("#divMenuList").html(JsMenuListHtml);
alert($("#divMenuList").html());
//hide num of raws dropdown
if (parseInt(JsTotalRecs) > parseInt(JsPageSize)) {
alert("Called1");
SetPaging(JsTotalRecs, parseInt(JsCurrPage));
}
else {
alert("Called");
$("#pager").html('');
}
$("#CurrPage").val(JsCurrPage);
SetAllCheckboxes();
}
else {
if ($("#CurrPage").val() > 1) {
//Error Message Pager
$("#product-table").html("");
$("#divSuccessMessage").html("");
alert(parseInt($("#CurrPage").val()));
GetListing(parseInt($("#CurrPage").val() - 1), parseInt(JsPageSize));
}
else {
$("#product-table").html("");
$("#divErrMessage").html("");
$("#divSuccessMessage").html("");
}
}
}
Regards

HTML response in JSON

I have a JSON file such as
[
{
"heading":"Apprenticeship Pathways",
"image":"http:\/\/www.domain.co.uk\/dfdf\/dfdf/images\/content\/join_our_team\/01.png",
"columns":[
{
"data":"<p>Curabitursapienligulasuscipitneccondimentu mneclaciniaavelitCraslaciniaodiositametvel itpellentesquefringillaPellentesquedapibus0 purusvitaemetusultricesultricesCrasvelorci mneclaciniaavelitCraslaciniaodiositametvel velitinhendreritarcicesultricesCrasvelorci5. velitinhendreritarcicesultricesCrasvelorci5.<\\p>"
},
The problem being when inputting the column data, "<\p>" is visible on screen, I.e. the escaped slash is not being removed.
function json_request( url, callback ) {
$.ajax({
url: url,
dataType: 'json',
success: function( data ) {
callback( data );
},
error : function(){
callback( false );
}
});
}
function build_html( $obj ) {
var $firstCol = $obj.columns.shift();
var $columns = '';
for( var i in $obj.columns ) {
$columns += '<div class="hori-con">';
$columns += $obj.columns[i].data;
$columns += '</div>';
}
var $return =
' <li>' +
' <div class="gridRow cf">' +
' <div class="twelveCol last">' +
' <div class="cf hori-con-inner">' +
' <div class="hori-con">' +
' <img src="' + $obj.image + '">' +
' <h3>' + $obj.heading + '</h3>' +
$firstCol.data +
' open' +
' </div>' +
$columns +
' <div>' +
' </div>' +
' </div>' +
' </li>';
return $return;
}
function filter_jobs(){
$('#join_our_team .sub-heading-bar a.nav-box').bind($bind , function(){
var $this = $(this),
$qsKey = 'filter',
$href = $this[0].href,
$basename = $href.split('?' + $qsKey + '=')[1],
$dataContainer = $('#joinOurTeamScroller ul.thelist');
if( typeof $basename !== 'undefined' ) {
json_request('./json/' + $basename + '.json', function( $data ){
$html = '';
if( $data !== false ) {
$.each( $data, function(key, val) {
$html += build_html( val );
});
}
$dataContainer.html($html);
});
}
return false;
});
}
Is there a standardised way of doing this or do I need to search and replace the slashes?

Google maps zoom broken

I've created a Google Maps overlay, but for some reason the zoom slider in the top-left of the map has stopped working. Have been trying to pick apart the code to fix it, but can't seem to find what is broken. Can someone have a look to see what I'm missing?
http://www.ucl.ac.uk/study/virtualtours/
My code is here:
<script type="text/javascript">
google.load("maps", "2");
google.load("jquery", "1.4.2");
var map;
var camera;
var side_bar_html = "";
var gmarkers = [];
function TileToQuadKey ( tx, ty, zl){
var quad = "";
for (var i = zl; i > 0; i--) {
var mask = 1 << (i - 1);
var cell = 0;
if ((tx & mask) != 0) cell++;
if ((ty & mask) != 0) cell += 2;
quad += cell;
}
return quad;
}
var uclvtTiles = function (a,b) {
var f = "http://www.ucl.ac.uk/prosp-students/access/virtual-tour/tourlayers/" + TileToQuadKey(a.x,a.y,b) + ".png";
return f;
}
function createUclVTSatMapType() {
var uclvtHybridLayer = new Array();
uclvtHybridLayer[0] = G_NORMAL_MAP.getTileLayers()[0];
uclvtHybridLayer[1] = new GTileLayer(new GCopyrightCollection('') , 17, 17);
uclvtHybridLayer[1].getTileUrl = uclvtTiles;
uclvtHybridLayer[1].getCopyright = function(a,b) {return "University College London, 2010";};
uclvtHybridLayer[1].getOpacity = function () {return 0.97;};//opacity of the non transparent part
if(navigator.userAgent.indexOf("MSIE") == -1) {
uclvtHybridLayer[1].isPng = function() {return true;};
}
var uclvtSatMap = new GMapType(
uclvtHybridLayer,
G_NORMAL_MAP.getProjection(),
'UCL Map',
{errorMessage:"", alt:"Show imagery with UCL Map"});
uclvtSatMap.getTextColor = function() {return "#000000";};
return uclvtSatMap;
}
function myclick(i) {
GEvent.trigger(gmarkers[i], 'click');
}
function addMarker(point, title, video, details) {
var marker = new GMarker(point, {title: title, icon:camera});
GEvent.addListener(marker, "click", function() {
if (details) {
marker.openInfoWindowTabsHtml([new GInfoWindowTab("Video", video),
new GInfoWindowTab("More", details)]);
} else {
marker.openInfoWindowHtml(video);
}
});
var id = gmarkers.length;
gmarkers.push(marker);
map.addOverlay(marker);
return id;
}
function flashMovieHTML(title, file) {
return '<div style="width:335px; height:260px">' +
'<b>' + title + '</b>' +
'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="325" height="244" ' +
'id="' + title + '" ' +
'title="' + title + '">' +
'<param name="movie" value="http://www.ucl.ac.uk/prosp-students/access/virtual-tour/' + file + '" />' +
'<param name="quality" value="high" />' +
'<param name="wmode" value="opaque" />' +
'<param name="swfversion" value="8.0.35.0" />' +
'<embed src="http://www.ucl.ac.uk/prosp-students/access/virtual-tour/' + file + '" ' +
'quality="high" ' +
'width="325" ' +
'height="244" ' +
'name="' + title + '" ' +
'type="application/x-shockwave-flash" ' +
'pluginspage="http://www.macromedia.com/go/getflashplayer">' +
'</embed>' +
'</object>' +
'</div>';
}
function addMarkersToMap() {
GDownloadUrl('campus.xml', function(doc) {
var xmlDoc = GXml.parse(doc);
var locations = xmlDoc.documentElement.getElementsByTagName("location");
var currentCategory = "";
for (var i = 0; i < locations.length; i++) {
var lat = parseFloat(locations[i].getAttribute("lat"));
var lng = parseFloat(locations[i].getAttribute("lng"));
var point = new GLatLng(lat,lng);
var title = locations[i].getAttribute("title");
var menu = locations[i].getAttribute("menu");
var video = locations[i].getAttribute("video");
var category = locations[i].getAttribute("category");
var details = locations[i].childNodes.length == 0 ? null :
'<div style="width:335px; height:260px">' +
locations[i].childNodes[0].nodeValue +
'</div>';
var id = addMarker(point, title, flashMovieHTML(title, video), details);
if (category != currentCategory) {
if (id > 0) {
side_bar_html += '</ul></div></div>';
}
side_bar_html += '<div class="collapsable">';
side_bar_html += '<h4 class="toggleCollapsableContent">' + category + '</h4>';
side_bar_html += '<div class="collapsableContent"><ul>';
}
side_bar_html += '<li><a href="javascript:myclick(' + id + ')">' + menu + '<\/a></li>';
currentCategory = category;
}
side_bar_html += '</ul></div></div>';
document.getElementById("right").innerHTML = side_bar_html;
$("h4.toggleCollapsableContent:gt(0)")
.addClass('closed')
.next('.collapsableContent').hide();
$("h4.toggleCollapsableContent").click(function () {
if ($(this).next($(".collapsableContent")).is(":hidden")) {
$(this).next($(".collapsableContent")).slideDown("fast");
$(this).removeClass("closed");
} else {
$(this).next($(".collapsableContent")).slideUp("fast");
$(this).addClass("closed");
}
});
});
}
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("mapDiv"));
map.setCenter(new GLatLng(51.52484592590448, -0.13345599174499512), 17);
map.setUIToDefault();
var uclvtSatMapType = createUclVTSatMapType()
map.addMapType(uclvtSatMapType);
map.setMapType(uclvtSatMapType);
camera = new GIcon(G_DEFAULT_ICON);
camera.image = "ucl-video.png";
camera.iconSize = new GSize(32,37);
camera.iconAnchor = new GPoint(16,35);
camera.infoWindowAnchor = new GPoint(16,2);
addMarkersToMap();
}
}
google.setOnLoadCallback(initialize);
Cheers,
G
The div that holds this image
http://www.ucl.ac.uk/prosp-students/access/virtual-tour/campus-map-key.png
is positioned absolutely above the map and it blocking access to everything underneath it.
This may help you:
#map img{max-width: inherit;}