How to strip a string from unwanted parts? - javascript

Given an url like this:
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg
How do i get it to be like
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,44_AL_.jpg
The issue I am having is with retrieving IMDB poster images, using this:
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: form.serialize(), // assuming the form has a hidden input with api_key name, containing your API key
crossDomain: true,
dataType: "jsonp",
success: function(data) {
window.console.log(data);
}
});
});
I get a json response like:
"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw##._V1_UX32_CR0,0,32,44_AL_.jpg"
I get no poster and the api i am using don't help, yet that thumbnail image is including various formats, one of which is 44_al which is what i would like to leave as a string in order to output it like:
function imdbLoad() {
var form = $("#usp-title").val();
var encodedTerm = encodeURIComponent(form);
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
q: encodedTerm
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
$.each(data.data.results, function(i, items) {
$("#imdb").append('<h2>'+i+'</h2>');
$.each(items, function(k, item) {
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ item.thumbnail +"'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
});
});
}
});
}
Unless anyone has any other way to grab the poster url

You can either use regex to replace string part that is not required
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var regex = /,.*(?=,)/g;
console.log(url.replace(regex, ''))
or split using comma(,) and join first and last part.
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var parts = url.split(',');
console.log(parts[0] + ',' + parts.pop())

This is a bit of a longer code as I have included few bits such as limiting the number of results but basically what I noticed is that after the ## the whole string is about image size. So instead of using a regex (that would be the answer for this specific question), I could simply add the dimension to the url as a string like:
<img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'>
Full code
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
api_key: "...",
q: form.find('input[name="q"]').val()
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
var thumbnailMod, limiteRes = 1;
if (data.data.results.titles !== undefined) {
$("#imdb").append('<h2>Titles</h2>');
$.each(data.data.results.titles, function(i, item) {
thumbnailMod = item.thumbnail.split('#.');
if (thumbnailMod.length > 1) {
if (limiteRes > 3) {
return;
}
limiteRes++;
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
}
});
} else {
console.log('No titles found for this search.');
}
}
});
});

Related

Download Base64 image through javascript

I am working on an image panel that displays the image titles and a link to download the image. I have an onclick function that gathers the base64 data from the database and then 'decodes' it. However, when I decode it I'm getting back a string of Chinese text..which is obviously not what I'm looking for.
$(document).ready(function() {
$('.downloadAttachment').on('click', function() {
var documentId = $(this).attr("data-id");
console.log(documentId)
$.ajax({
dataType: 'json',
//data: id,
async: false,
type: 'GET',
//url: baseUrl + 'rest/incdDocument/getAll?branchCode=' + brCode + '&receivedDate=' + receiveDate + '&complaintID=' + cId + '&incidentID=' + incidentId+ '&documentID='+documentId,
url: baseUrl + 'rest/incdDocument/get?branchCode=009&receivedDate=03/10/2017&complaintID=170&incidentID=3'+'&documentID='+documentId,
success: function(data) {
if (data) {
var image = Base64.decode(data.data);
window.open(image, '_blank');
}
},
error: function(request, status, error) {
console.log(error)
}
});
return false;
})
});
Is there a better way to extract this data and actually turn it into an image?
Searching for like this ?
var image = new Image();
image.src = data; (complete base64 sting with imagetype)
Download Image
Make a download.php file with return the a image with
header('Content-type:image/png'); or other image type

Handling of click events in jQuery(For Like and Unlike button)

I am trying to create a Like-Unlike system using AJAX and jQuery. The "like" event seems to work properly, but when I want to "unlike" the event is not responding. Any suggestions to solve this problem is appreciated.
$(document).ready(function() {
$(".like").click(function() { //this part is working
var item_id = $(this).attr("id");
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('like');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('liked');
$('a#' + item_id).html(data);
}
}
});
});
$(".liked").click(function() { //this part is not working
var item_id = $(this).attr("id");
console.log(item_id);
var dataString = 'item_id=' + item_id;
$('a#' + item_id).removeClass('liked');
$('a#' + item_id).html('<img src="images/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
alert('you have liked this quote before');
} else {
$('a#' + item_id).addClass('like');
$('a#' + item_id).html(data);
}
}
});
});
});
$(".like") and $(".liked") are retrieved when the document is ready but don't get updated when you add/remove classes from an element.
If you assign a more generic class the vote elements like 'like-toggle' you would be able to do the following:
$(document).ready(function() {
$('.like-toggle').click(function(event) {
if ($(event.target).hasClass('like') {
// Call your unlike code, replace like with liked.
} else {
// Call your like code, replace liked with like.
}
});
});
This will work because the like-toggle class never gets removed from the elements and thus the elements which are present when the document is ready will keep functioning.

Repopulating Image Picker select control with new data after ajax call

I am using this Image Picker jQuery plugin (http://rvera.github.io/image-picker/) and I'm facing a problem with the following:
Repopulating the select control with new data after ajax call.
$.ajax({
type: "GET",
url: requestURL,
dataType: 'json',
success: function(result)
{
$.each(result, function(i, obj) {
console.log(obj.description);
$('#cake-filling-types-select')
.append($("<option data-img-src='" + obj.image + "'></option>")
.attr("value", obj.code)
.text(obj.description));
});
$("#cake-filling-types-select").imagepicker({
show_label : true
});
$("#cake-filling-types-select").data("picker").sync_picker_with_select();
}});
For more details please find the issue here: https://github.com/rvera/image-picker/issues/79
Thanks.
The issue is solved. With the help of #ArmindoMaurits # GitHub, so using the ' $("#cake-filling-types-select").empty();' is fine for clearing this plugin select.
Also, for the other issue where some items are not getting into the select control, I found that these the ones that is missing the img src.
Updated working code:
`$.ajax({
type: "GET",
url: requestURL,
dataType: 'json',
success: function(result){
$("#cake-filling-types-select").empty();
$.each(result, function(i, obj) {
if(obj.image != null)
{
var imgSrc = obj.image;
}else{
imgSrc = '';
}
$('#cake-filling-types-select')
.append($("<option data-img-src='" + imgSrc + "'></option>")
.attr("value", obj.code)
.text(obj.description));
});
$("#cake-filling-types-select").imagepicker({
show_label : true
});
}});`

insert received information into table on html

I am doing on a instagram api, and I get information from server including user profiles and two more kinds. I want to put the information in a table on html. Each row is related to a username(since I searched for username), and there are profiles and two more things on each row. I am a little confused about how to do that.
here is my code:
var searchUsers = function(query,count){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
data: {
q: query,
count: count,
access_token: access_token,
},
url: "https://api.instagram.com/v1/users/search",
success: function(data) {
// placing the images on the page
console.log(data);
if (data.data.length>0){
var resultShow = $("#users_result");
for (var i in data.data){
resultShow.append("<img src='" + data.data[i].profile_picture + "'></img>");
// var username = "https://www.instagram.com/"+ data.data[i].username;
// console.log(username);
resultShow.append("<a target='_blank' href = 'https://www.instagram.com/"+data.data[i].username+"'>user profile</a>");
// var id = data.data[i].id;
// console.log(id);
$.ajax({
url: 'https://api.instagram.com/v1/users/' + data.data[i].id + '/media/recent/',
type: "GET",
dataType: "jsonp",
data: {access_token: access_token},
success: function(data2){
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
},
error: function(data2){
console.log(data2);
}
});
}
} else {
resultShow.html("Noting found!");
}
},
error: function(data){
console.log(data);
}
});
};
You can change almost any value in a page using the innerHTML property.
Ex:document.getElementById("demo").innerHTML = "Paragraph changed!";
http://jsfiddle.net/blazeeboy/fNPvf/
To change the values inside a table, just assign an ID to it and change with your Javascript function.
In your case, I would suggest inserting any Javascript parameter between line 31 and 32.
success: function(data2){
var title = document.getElementById('title');
var username = "https://www.instagram.com/"+ data.data[i].username;
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
It will write the username into the table with id "title", if you need more than one table value, you'll need to make a array and use the for loop to insert an specific value into a specific table, tr, etc... id
success: function(data2){
//tableids are the ids of each table row or column in the order you wanna write them
var tableids = ['0', '1', '2'];//starting at 0
var username = "https://www.instagram.com/"+ data.data[i].username;
var title = document.getElementById(tableids[i]);
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
Hope it was clear enough

Json data in a next and previous button

I have to use a AJAX call to get Json data after clicking next and previous buttons. Json data should contain blog content displayed after clicking next or previous. Any suggestions how my function should look like? So far I have only:
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).success(function (data) {
$.each(data, function (key, val) {
$('#blogcont').append(key+ val);
});
return false;
});
}
And my Json file is only a test file:
{"one":"test1", "two":"test2", "three":"test3" }
Sorry I am a beginner!!!!
Thanks
Your $.ajax() syntax is incorrect
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
}
});
return false;
}
or
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += "<p>" + key + ":" + val + "</p>";
});
$('#blogcont').html(content);
});
return false;
}
Try this
function getPrev() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json"
}).done(function(data) {
var content = "";
$.each(data, function(key, val) {
content += '<p>' + key + ':' + val + '</p>';
});
$('#blogcont').html(content)
.find('p')
.hide()
.first().show();
$('button.next').click(function() {
$('#blogcont').find('p:visible')
.hide()
.next('p').show();
});
});
return false;
}
How about storing the JSON data as a variable, which you can then access using an index on click?
var jsonData;
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
jsonData= data;
}
});
var clickIndex = 0;
$('.prev').click(function() {
if(clickIndex > 0) {
clickIndex -= 1;
}
get(clickIndex);
});
$('.next').click(function() {
clickIndex++;
get(clickIndex);
});
Your get function would then accept the index and find the JSON property:
function get(i) {
var item = jsonData[i];
}
Note that you would need to add an if statement to check whether you have reached the index limit on click of .next. Also, this is fine for a test JSON file, but a better solution would be to be able to request just one relevant item from a web service returning the JSON.

Categories

Resources