html a onclick window open not working on ajax - javascript

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+'';

Related

AJAX POST of tinyMCE contents - Character encoding of table entities

I'm using the tinyMCE editor plugin in my webpage.
When I use a simple HTML page post to post the contents to the backend PHP and save them to a database or file, all seems OK.
When I try to do the same using an AJAX post, I am finding it impossible to prevent encoding issues.
In particular (I'll escape it here) \&\n\b\s\p\; is being converted to  and a "-" character is being converted to �
I've tried a few suggestions but with little luck.
The suggestion is that it is either an issue with my charset or encoding.
My save function is as follows:
function letterSave(newfile,fname){
var newDate = new Date;
var uniq=newDate.getTime();
var input = $('#myTextareastdletter');
var contents=input.val();
var context='<?=(!strcmp($sessobj->mode,"SA_ViewAbs")?"A":"S");?>';
// alert(fname);
$.ajax({
type: "POST",
url: '<?=auto_version("./SVajaxSaveDocContents.php")?>?duff='+uniq,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {'S_sessid' : '<?=$sessobj->sessionid?>', 'context' : context, 'contents' : encodeURIComponent(contents), 'fname' : fname, 'newfile' : newfile},
success: function(data){
data = JSON.parse(data);
fname=data[0];
newLetterList=data[1];
if (fname != 'FAIL') {
alert ('OK: Letter Contents Saved to File ('+fname+').');
var versionOutput = $('#popupOutput');
versionOutput.html('');
var box = $('#popupDisplay');
var cover=$('#coverDiv');
box.css({
display:"none"
});
cover.css({
display:"none"
});
var letterOutput = $('#AbsenceLetters');
letterOutput.html(newLetterList);
} else {
alert ('Sorry: Failed to Save Letter Contents!');
}
},
error: function(data){
alert ('Sorry: Failed to Save Letter Contents!');
// console.log(data);
// console.log('error');
}
});
}
As you can see, I've been playing with setting the contentType and using encodeURIComponent().
Any help would be appreciated.
Cheers
In order to avoid these encoding issues, don't use .val on the textarea that the tinyMCE instance is attached to. Instead, you can utilize tinyMCE's built-in getContent method like so:
tinyMCEInstance.getContent()

How to use window.open in onclick inside each loop

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+'\'

getting left space while dynamic added row in javascript

I am adding dynamic span with onclick .
$.ajax({
url:path,
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formdata,
success: function (result) {
if(result==1){
for (var FileName of formdata.entries())
{
var fileName=FileName[0].trim();
**$("#"+PreviewControl).append('<span onclick="showaleart("'+fileName+'")">'+fileName+'</span>');
$("#"+hdnHasFile+"").val(1) ;**
}
}
}
});
function showaleart(filename){
alert(filename);
}
But when i click on that span element its giving error as Uncaught SyntaxError: Unexpected token }
But if i replace onclick="showaleart("'+fileName+'")" to onclick="showaleart()" with out any argument.
It does not give error.and the click is working.
when i click on element and inspected the element . it was creating element like this.
<span onclick="showaleart(" bank.jpg")"="">Bank.jpg</span>
You aren't using quotations properly, the second set of " renders the bank.jpg outside of the onclick. You need to use different type of quotes and escape them. Try this instead:
'<span onclick="showaleart(\''+fileName+'\')">'+fileName+'</span>'
or
`<span onclick="showaleart('${fileName}')">${fileName}</span>`

Why do I get undefined when displaying value in a global variable?

I just don't get it, obviously. I've tried setters and getters, self invoking functions, you name it. It's like the click handler is returning a value but there's no way for me to keep it?
This is my code in the first file request.js
var testId = (function (inId) {
var citeId = inId;
return citeId;
})();
function mainAjax() {
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
});
}
var promise = mainAjax();
this is the code in my second file requestMain.js,
promise.done(function (json) {
var linkBase = "http://www.sciencebase.gov/catalog/item/";
var link = "";
var itemId = "";
var urlId = "";
$.each(json.items, function(i,item) {
link = linkBase + this.id;
$('#sbItems').append('<li><b>' + this.title + ' - </b>' + this.summary + '</li>');
});
$('#sbItems a').on('click', function (e) {
e.preventDefault();
var str = $(this).attr('id');
if (str.length == 7) {
itemId = str.slice(5,6);
}
else if (str.length == 8) {
itemId = str.slice(5,7);
}
testId = json.items[itemId].id;
alert(testId);
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
This webpage displays a list of links. A link could have some more information that I want displayed on a second webpage or it could have nothing. So when a link is clicked I need to store/save/keep the id from the link so that I can use it in the url to make another ajax request, because until I get the id the ajax request for the next page will have no idea what information to ask for.
For now I'm simply doing this
alert(testId);
But what I'm trying to do is this,
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' + testId + '?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
// Then doing something with json.something
testId would be used in the url and it would change depending on the link that was clicked on the previous page. The ajax call is totally dependent on the click event and is displayed on a separate webpage with new information.
And this would be in my third file requestCitation.js which currently gives me a big undefined when doing
alert(testId);
I think this is a scope issue, but how can I store the value returned from a click??? So that I can then use it globally? It seems like the value disappears outside of the scope as if there was never a click at all even thought I'm storing it in a variable?
the html for the first page has script tags for request.js and requestMain.js and the second page has script tags for request.js and requestCitation.js, so they can both see the variable testId.
Thanks for the help!
Here's the jsfiddle
These are the links and when a link is clicked
Your testId is holding the value retuned by the function you're calling, and since the function returns its argument and you've called it without arguments, it will be undefined:
var testId = (function (inId) {
var citeId = inId;
return citeId; //returns the argument
})(); // called with no argument
I'm not entirely sure what you're trying to do but if you're trying to keep the data returned from the AJAX request as a global variable, I would have thought it was done using something similar to the below.
E.g.
var promise = '';
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
data: '';
success: function(data){
promise = data;
}
});
But as I said I'm not understanding fully so I could be very wrong with my answer.

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?

Categories

Resources