How to use window.open in onclick inside each loop - javascript

I am trying to show page content inside PhoneGap app.
This works very fine:
google.com
When I click on the link google is loaded inside the app.
I am retireibving the posts data using WordPress Rest API.
For that I am using this:
getPosts: function() {
var rootURL = 'https://example.com/wp-json/wp/v2/posts/';
$.ajax({
type: 'GET',
url: rootURL,
dataType: 'json',
success: function(data){
$.each(data, function(index, value) {
console.log(value.featured_image);
$('ul.homepost-list').append('<li class="homepost-list__item">' +
'<a href="'+value.link+'">'+
'<img width="100" height="75" src="'+value.fimg_url+'" alt="'+value.title.rendered+'"/>'+
'<h3>'+value.title.rendered+'</h3>' +
'<p>'+value.excerpt.rendered+'</p>'+
'</a>'+
'</li>');
;
});
},
error: function(error){
console.log(error);
}
});
}
but the when click on posts it opens in the browser.
to open it inside the app I have to use the onclick function like this: google.com
So I've changed like this:
getPosts: function() {
var rootURL = 'https://example.com/wp-json/wp/v2/posts/';
$.ajax({
type: 'GET',
url: rootURL,
dataType: 'json',
success: function(data){
$.each(data, function(index, value) {
console.log(value.featured_image);
$('ul.homepost-list').append('<li class="homepost-list__item">' +
'<a href="#" onclick="'+window.open(''+value.link+'', '_self ', 'location=yes')+'">'+
'<img width="100" height="75" src="'+value.fimg_url+'" alt="'+value.title.rendered+'"/>'+
'<h3>'+value.title.rendered+'</h3>' +
'<p>'+value.excerpt.rendered+'</p>'+
'</a>'+
'</li>');
;
});
},
error: function(error){
console.log(error);
}
});
}
But now the anchor onclick value is NULL onclik null
I think this is because of this line has a syntex error'<a href="#" onclick="'+window.open(''+value.link+'', '_self ', 'location=yes')+'">'+
How do I have to change this syntax line to get it work?
It's just a simple syntax error I know but I could not figure it out.

You need to work on how you add strings and variables as well as single and double quotes. See fiddle here https://jsfiddle.net/designtocode/u3o57jr2/3/
onclick="'+window.open(''+value.link+'', '_self ', 'location=yes')+'">'+
Needs to be:
onclick="window.open(\''+value.link+'\', \'_self \', \'location=yes\')">
This means the onclick and window.open needs to pass as strings and value.link needs to be a variable. Since we are using single quotes to escape javascript code, we need to add \ before the single quote if you need it as a string.
I hope this makes sense and will help you in future.

You need to escape your single quotes
window.open(\'+value.link+'\'

Related

html a onclick window open not working on ajax

Below is the code:
$.ajax(
{
url: "savePart",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (jsonStr)
{
var result = JSON.parse(jsonStr);
var materialQualification = ''+mqFormat+'';
var newrow = $('<tr class="trClick" id="'+result.formID+'" data-toggle="modal"><td align="center" class="number">'+materialQualification+'</td></tr>';
$("#tData tbody").prepend(newrow);
}
});
When above code execute, window.open is not working. When I click <a></a>, it's not show me new window open.
Is there any way how to set it? Or Am I do something wrong there?
UPDATED:
When <a></a> clicked, it show me error in console:
Uncaught SyntaxError: Unexpected token }
Thanks.
Replace this line in your code and try. There is a mashup with a " and '. I use ' with slace \' instead of " inside window.open function.
var materialQualification = ''+mqFormat+'';
Onclick not working because of " double quote in the below line.
var materialQualification = ''+mqFormat+'';
Add \ before " double quote and add ' single quote in place of " double quote in window.open function., checkout below line
var materialQualification = ''+mqFormat+'';

How to get posts of a specific user with Instagram API?

I would like to have the recent posts of an specific user, like Banksy.
I came up with the following, but it will give me an error of:
GET https://api.instagram.com/v1/users/banksy/media/recent/?access_token={token}&callback=jQuery11110924438442569226_1445956181244&_=1445956181245
My ajax call looks like this:
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/banksy/media/recent/?access_token={token}",
success: function(response) {
console.log('jfsdahuifhasudh')
console.log(response);
// placing the images on the page
// for (var i = 0; i < 6; i++) {
var html = '<a href="' + response.data[i].link + '" >'+
'<img src="' + response.data[i].images.low_resolution.url + '" alt="thumbnail" /></a>';
$(".instafeed").html(html);
// }
},
error: function(data) {
console.log('We have a problem!');
}
});
You're using the username in your query; banksy in your case. Resolve the username into ID then use the id in your query. For example;
https://api.instagram.com/v1/users/45951573/media/recent/?access_token={token}
*The API will return posts only if the account is public.
Edit
To get posts tagged with a specific hashtag use:
https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={token}
Further reading: Instagram API; Tags
Update
instaJS is a jQuery plugin I wrote in past. What makes this plugin unique is that it accepts username instead of forcing users to resolve their id. Completely Free to use :), and of course contribution is always welcomed InstaJS on Github

get only specific data in success message from ajax

i have an ajax call and i am getting a response from the call. the code is like this:
<div id="flow_#id#~#sid#" style="margin: 0 10px 0 0;float:right;height:150px;" class="code">
<img src="/assets/codes/#code#.jpg" style="max-height: 230px;">
</div>
What i am doing is the response i get from my ajax, i want to replace the contents of the div tag with the value coming from my ajax success
ajax call is like this
$.ajax({
url: 'bc.cfm?ID=' + getID + '&ssID=' + getSID,
type: "GET",
cache: false,
success: function(data){
$("#flow_" + getID + "~" + getSID + " img:last-child").remove();
$("#flow_" + getID + "~" + getSID).html(data);
}
});
But a complete html page is coming in success, i can the img in firebug, but a complete html source is there, how can i extract that img tag and replace with the one which is already there above [the id is going to be same for both for identification, only 1 will be used, we will be removing and adding again]
If you want to just extract image from the response, you can try this. I have not tested the code, but it should work. Please check it.
success: function(data){
// get the image tag from the response
var $img = $(data).find('img');
$("#flow_" + getID + "~" + getSID + " img:last-child").remove();
// replace
$("#flow_" + getID + "~" + getSID).html($img.html());
}
Use JSON instead
for example:
javascript
$.ajax({
type: 'POST',
url: 'yourphpfile.php',
dataType: 'json',
success: function (x) {
console.log(x.imgtag); // img
}
});
return false;
php
<?php
header('Content-Type: application/json');
$output=array();
$output['imgtag']='<img src="myimg.jpg">';
echo json_encode($output);
?>
Place whatever you want into the $output array (such as img tags) and you may easily access it in JavaScript.

java script - Cant send parameter to function from info window in google map marker info window

I'm showing up some markers on a map. when clicked, an info window appear. this window contains 2 button each send ajax request. the problem is that when I send any thing (Except a marker parameter below) to the button onClick event it does not work. and I get the error "adminmap.html:1 Uncaught SyntaxError: Unexpected token ILLEGAL" on the first line of the HTML page not the script file at all.
function handleButtonApprove(id) {
//error happens here when I send any parameter except marker8(defined below)
//console.log(id);
$(document).ready(function () {
$.ajax({
type: "POST",
url: VERIFY_OBSTACLES_URL,
//data: { markerID:sentID , approved:0 },
success: function (data) {
alert(data);
}
});
});
}
function handleButtonReject() {
$(document).ready(function () {
$.ajax({
type: "POST",
url: VERIFY_OBSTACLES_URL,
//data: { markerID:marker.id , approved:0 },
success: function (data) {
alert(data);
}
});
});
}
function attachInfo(marker8, num) {
//var markerID = marker.get("id");
//console.log(markerID);
var infowindow = new google.maps.InfoWindow({
//Here is the error , if I sent num.toString, num or any string , it does not work. If send marker8.getPosition() for example it works. May I know the reason ?
content: '<div id="info_content">Matab Info</div> <button onclick="handleButtonApprove(' + num.toString() + ')">Verify</button> </br> <button onclick="handleButtonReject()">Remove</button>'
});
google.maps.event.addListener(marker8, 'click', function () {
infowindow.open(marker8.get('map'), marker8);
});
}
When you like to provide a (non-numeric) string as argument to handleButtonApprove(), you must wrap the string with quotes:
content: '<div id="info_content">Matab Info</div> \
<button onclick="handleButtonApprove(\'' + num.toString() + '\')">\
Verify</button>\
</br> <button onclick="handleButtonReject()">Remove</button>'
But this can't be the issue, because when you don't use the quotes, the error should be a undefined variable and not a syntax-error. What exactly is num?

Javascript replace error

I have one problem with function in Javascript. When I insert text in textarea, function sends text to PHP script with AJAX, but I have problem when I insert two or three words, e.g Bosnia and Herzegovina then the script does not work. I used string replace :
function provjeraDrzave(rijec) {
rijec = rijec.replace(" ", "%20");
$.ajax({
type: "GET",
url: "/drzava.php?slovo=" + randomslovo + "&drzava=" + rijec,
success: function (odgovor) {
$('#rezultati').replaceWith($("<span id='rezultati'>" + odgovor + "</span>"));
},
error: function () {
alert('Doslo je do pogreske');
}
});
}
It should work as follows: When I insert Bosnia and Herzegovina that must change to Bosnia%20and%20Herzegovina but that change to Bosnia%20and Herzegovina and that does not work. Where is the problem ??
Why don't you use, for example, the native encodeURIComponent function, which is made for this?
Or, even better, let jQuery take care of URL encoding for you, using the data config param:
function provjeraDrzave(rijec) {
$.ajax({
type: "GET",
data: {
slovo: randomslovo,
drzava: rijec
},
url: "/drzava.php",
success: function (odgovor) {
$('#rezultati').replaceWith($("<span id='rezultati'>" + odgovor + "</span>"));
},
error: function () {
alert('Doslo je do pogreske');
}
});
}
jQuery $.ajax can receive url arguments via the data property and should automatically serialize it for you.
data
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests... Object must be Key/Value pairs...
$.ajax({
type: 'GET',
url: '/drzava.php'
data : {
'slovo' : randomslovo,
'drzava' : rijec //no need to replace
}
success: function (returndata) {...},
error: function () {...}
});
If you absolutely want to do this way try
rijec = rijec.replace(/\ /g, "%20");
but encodeURIComponent would be more appropriate.

Categories

Resources