$('#' + postFormId ).html( xml ) throwing Unexpected call to method error - javascript

Edit:I have tried jquery versions 1.11.3 and 1.4.2
The following code throws the error "Unexpected call to method or property access" when emulating previous versions of ie(5 and 7). Using this emulation is not optional as it is set by a third party IT. It works fine in IE8 and there was a version that was essentially the same code (I copy and pasted it, and made a couple of changes) used to work in 5 and 7.
Using console.logs, I'm fairly certain that the issue is in $('#' + postFormId ).html( xml ) though I could be wrong.
if( punchOutCartPage != "SalesOrder" ) {
$(document).on('click','#btn-proceed-checkout',function(){
var itemsXML = parseShoppingCart();
var headerXML = "\t<header>\n\t\t{sellerId}\n\t\t{buyerID}\n\t\t{sessionId}\n\t</header>";
var shoppingCartXML = createNetSuiteShoppingCart( headerXML, itemsXML );
var form = $("#cart");
var form_action = form.attr("action");
$.ajax({
url:'/app/site/backend/emptycart.nl?c=',
context: document.body,
success: function(data){
var form_serialized = form.serialize();
$.post(form_action, form_serialized,
function (val) {
postToPunchOutUrl(punchOutUserCartUrl, shoppingCartXML);
}
);
}
});
return false;
});
}
function parseShoppingCart() {
}
function createNetSuiteShoppingCart( headerXML, itemsXML ) {
var parentCompany =localStorage.StrparentCompany;
var account =localStorage.Straccount;
var sessionId = localStorage.StrpunchOutSessionId;
headerXML = headerXML.replace("{sellerId}", "<sellerID>" + encodeXML(account) + "</sellerID>");
headerXML = headerXML.replace("{buyerID}", "<buyerID>" + encodeXML(parentCompany) + "</buyerID>");
headerXML = headerXML.replace("{sessionId}", "<PunchOutSessionID>" + encodeXML(sessionId) + "</PunchOutSessionID>");
itemsXML = "<NetSuiteSellerPunchOutShoppingCart>\n" + headerXML + "\n" + "<itemList>\n" + fezzik + "</itemList>\n" + "</NetSuiteSellerPunchOutShoppingCart>";
itemsXML = encodeXML(itemsXML);
var shoppingCartXML = '<input type="hidden" name="shoppingcart-urlencoded" value="{url-encoded-raw-xml}">';
return shoppingCartXML.replace("{url-encoded-raw-xml}", itemsXML);
}
function postToPunchOutUrl( url, xml ) {
var postFormId = "poomform";
$('#' + postFormId ).html( xml );
$('#' + postFormId ).attr( "action", url );
document.forms[postFormId].submit();
}
function encodeXML(string) {
return string.replace(/\&/g, '&' + 'amp;').replace(/</g, '&' + 'lt;').replace(/>/g, '&' + 'gt;').replace(/\'/g, '&' + 'apos;').replace(/\"/g, '&' + 'quot;');
}

This issue was caused by the document mode emulation itself. When internet explorer emulates document mode 5 or 7, it wraps a form tag around your forms in certain cases. So this <form method="POST" name="poomform" id="poomform" action="https://www.example.net"></form> became (I didnt copy it, but approximately)
<form><form method="POST" name="poomform" id="poomform" action="https://www.example.net"></form></form>
Which then throws the unexpected call to method error.
I worked around this by adding the form with javascript after the page had loaded, so I replaced the form in the html with <div id="poomformholder"></div>
and then added a line of jquery to my postToPunchOutUrl function to look like:
function postToPunchOutUrl( url, xml ) {
$('#' + "poomformholder" ).html("<form method=\"POST\" name=\"poomform\" id=\"poomform\" action=\"https://www.example.net\"></form>");
//The id name of our form.
var postFormId = "poomform";
$('#' + postFormId ).attr("action",url);
$('#' + postFormId ).html(xml);
And now everything works. Hopefully this helps someone in the future and thank you for your help!

Related

access to DOM add dynamiclly, getScript, ajax

I use jQuery ajax to read context on my page dynamicly. But part of DOM is load in javaScript function call by getScript in ajax .done. But just after I load new content I need to get elements by class and use it in next function. Unfortunatly I can't find elements, that I create in javaScript function, and script with that function I call using jQuery getScript.
ok, my code:
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html',
success: function(responseText){
$('#text').html(responseText); // responseText has only container <div id="insideText"></div> that I use in one function and load there by html() several divs. One of this div has class 'translate'. I need it in function Translator
}
})
.done(function(){
$.getScript(script); // here I call script where I load several divs to #insideText
Translator($('.active').attr('data-lang')).getTranslation() // part of function have to find all div.translate, but can't find it if they're load in script call in getScript. And this is a problem.
})
})
})
I hope, I explaine my problem quite clear. If not, plaese ask, I'll try again.
There's some way to do that?
//update//
After this script, call by getScript I still have problem with second 'done':
const Presenter = function(){
var presented, show, fullDesc, cont;
presented = [
{
url: 'demo/colorsGame/',
name: 'Graj w kolorki!',
desc: 'Graj w kolorki! Wybierz taki sam kolor, w jakim napisana jest nazwa wylosowanego koloru. Spiesz się, czas ucieka coraz szybciej i szybciej. Uważaj, bo mózg może cię oszukać i uznać za ważniejsze to, co jest napisane, a nie to co widzisz. Zobacz ile punktów jesteś w stanie zdobyć zanim popełnisz trzy błędy. Ćwicz swoją koncentrację.'
},
{
url: 'demo/sampleUserProfile/',
name: 'Sample User Profil',
desc: 'Mała próbka możliwości reactJS. Wkonany z użyciem biblioteki reactJS, menadzera pakietów webpack oraz na środowisku nodeJS przykładowy profil użytkownika. Like-uj i obserwuj do woli, a jeśli chcesz, wypowiedz się pod profilem.'
}
];
show = function(url, desc, name) {
fullDesc =
"<a href ='" + url + "'>" +
"<h1 class='translate'>" + name + "</h1>" +
"</a>" +
"<div>" +
"<p class='translate'>" + desc + "</p>" +
"</div>";
cont =
"<div id='webmin' class='clearfix'>" +
"<div>" +
fullDesc +
"</div>" +
"<div>" +
"<iframe src='" + url + "' scrolling='no'>" +
"ups, twoja przeglądarka nie obsługuje ramek" +
"</iframe>" +
"</div>"+
"</div>";
return cont;
};
return {
show: show,
presented: presented
}
};
display = function(){
var len, url, name, desc;
len = Presenter().presented.length;
for(let i = 0; i <= len; i++){
url = Presenter().presented[i].url;
name = Presenter().presented[i].name;
desc = Presenter().presented[i].desc;
$('#insidetext.apps').append(Presenter().show(url, desc, name));
}
};
display();
Hmm, I'm wondering, if iframe is not a problem here? And don't let script to be done to end?
getScript is just another ajax call and returns an xhr object which exposes done and fail methods. Use those methods to ensure your dom is properly loaded before trying to access it.
$(document).ready(function() {
$('.link').click(function(){
var subpage = $(this).attr('data-subpage');
var src = 'subpages/'+ subpage + '/' + subpage +'.php';
var script = 'subpages/'+ subpage + '/js/' + subpage +'.js';
$.ajax({
url: src,
context: document.body,
dataType: 'html'
})
.done(function(responseText){
$('#text').html(responseText);
$.getScript(script).done(function() {
Translator($('.active').attr('data-lang')).getTranslation() ;
}
})
})
})
Also, you should implement the .fail methods, in case your ajax requests fail.

Jquery or Javascript Redirect to Controller/Action

I have the following code which works on the first time around:
$("#CompDD").change(function () {
//var parts = (window.location.pathname.split("/"));
var ctrlName = '#ViewContext.RouteData.Values["Controller"].ToString()';
var actnName = '#ViewContext.RouteData.Values["Action"].ToString()';
var url = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//delete ctrlName;
// delete actnName;
//window.location = ($(location).attr('href') + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//window.location = (ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
//$(location).attr('href', url);
window.location.href = url;
//alert(ctrlName + "\n" + actnName);
});
However on subsequent changes of the drop down in question (#CompDD) it will add another controller/action to the end of the link, ex. it adds another "Patrons/Index" to the end of the existing "Patrons/Index", thenit adds the searchsrting variables etc.
Please excuse the comments and stuff on my code. How do i get Jquery (or javascript) to redirect without appending the controller name and action names over and over, or whats the best way to do this?
EDIT: Such an easy fix! I had to add the root slash to the URL string, example this worked:
var url = ("/" + ctrlName + "/" + actnName + "/?SearchString=" + $('#CompDD option:selected').text() + "&atton=" + $('#AttDD option:selected').val());
Notice the forward slash at the start of the string I construct....Yikes!
Use the Url.Action helper method to build path to action methods.
$("#CompDD").change(function () {
var baseUrl="#Url.Action("Home","Search")";
alert(baseUrl);
// Now append your query string variables to baseUrl
// Ex : baseUrl=baseUrl+"?searchString=testing";
window.location.href=baseUrl;
});
Assuming you want to navigate to the search action method in Home controller.
function RedirectUrl() {
if (domElement.textfor.val() == "Index") {
window. location.href = E_host.AppVar.AppHost + "/Home/index";
}
}

jQuery read XML URL

My below code working well but i need to import XML data from xml URL not from HTML file like this
if i need to retrieve image from XML how i can do that.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(document).ready(function(){
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).find('show').each(function(){
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
//alert($('#show_table').html());
})
all what i need is change this var xml = "9/8 ... " to let the JQuery code read from the ONLINE URL
If you need to load XML data from the URL, you need to execute AJAX request, it may be something like this:
$(function() {
$.ajax({
type: "get",
url: "http://yoursite.com/yourfile.xml",
dataType: "xml",
success: function(data) {
/* handle data here */
$("#show_table").html(data);
},
error: function(xhr, status) {
/* handle error here */
$("#show_table").html(status);
}
});
});
Keep in mind, if you use AJAX you can place .xml file on the same domain name. In other case you need to set up cross-origin resource sharing (CORS).
EDITED:
I modified your code, now it appends td element to your table. But xml is still inside html.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(function() {
$(xml).find('show').each(function() {
console.log(this);
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append($(html));
});
});
But you need to modify your html file, check my solution here: http://jsfiddle.net/a4m73/
EDITED: full solution with loading xml from URL
I combined two parts described above, check here: http://jsfiddle.net/a4m73/1/
Use jquery-xpath, then you can easily do what you want like:
$(xml).xpath("//shows/show");
if you want know more about xpath just take a look on XML Path Language (XPath) document.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>";
$(document).ready(function () {
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).xpath("//shows/show").each(function () {
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
})

Is there any size limitation for ajax post?

I'm posting ckeditor content via Ajax to php. But getting 4-5 sentence of posted material in my db table. I wonder, Is there any size limitation for ajax post? is there any way to post big text contents via ajax?
My js looks like that
function postViaAjax(autosaveMode) {
var name = $("#name").val();
var title = $("#title").val();
var menu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
var id = $("#id").val();
if (parentcheck == 0) {
var parent = parentcheck;
} else {
var parent = $("#parent").val();
}
var content = CKEDITOR.instances['content'].getData();
var dataString = 'name=' + name + '&title=' + title + '&menu=' + menu + '&parentcheck=' + parentcheck + '&id=' + id + '&parent=' + parent + '&content=' + content;
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
var message = result.msg;
var err = result.err;
var now = new Date();
if (message != null) {
if (autosaveMode) {
$('#submit_btn').attr({
'value': 'Yadda saxlanıldı ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
} else {
$.notifyBar({
cls: "success",
html: message + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
}
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
}
});
};
The HTTP specification doesn't impose a specific size limit for posts. They will usually be limited by either the web server or the programming technology used to process the form submission.
What kind of server do you use?
There isn't any size limitation for POSTs in HTTP.
Maybe you have an & in your content variable. Then everything after that would be stripped after that.
Other than that what type do you use for your data column in the database? Is it, by any chance, something like varchar(1000)? Then anything bigger would also get stripped.
Check what you actually receive on the server end, so you know if you've got a problem with the code or the database.
You have a limitation on the Apache server. Look for LimitRequestBody directive.
This may be helpful:
http://gallery.menalto.com/node/14870
In theory the limits on AJAX requests are the same on all the other requests, so it depends on your web server/app setup. See also Max length of send() data param on XMLHttpRequest Post

Use jQuery to insert a script which includes a function?

I am trying to append a line of JavaScript to a div dynamically, but it seems that when I run the .append() call, the browser sees a function() call within that line as an actual function instead of an actual string:
var startDate = 0
...
function insertCalendar(){
var divName = "div[name=StartDate" + startDateNum + "]";
$(divName).append("<script>Calendar.setup({ trigger : 'StartDate" + startDateNum + "', inputField : 'StartDate" + startDateNum + "', onSelect : function() { this.hide() } });</script>");
startDateNum++;
}
At the call to .append() the JavaScript console returns "Uncaught SyntaxError: Unexpected end of input," and it seems to mess with the function insertCalendar. I'm fairly certain I'm not missing a quote...
Let me know if this is too vague as this is my first question here. Thanks!
You can create a script tag, and then add the javascript.
var jstag=document.createElement('script');
jstag.setAttribute("type","text/javascript");
jstag.appendChild(document.createTextNode(" Javascript code goes here "));
document.appendChild(jstag);
Got the answer thanks to Anzz, mixed it with some AJAX:
var startDateNum = 0;
...
function setNewCal(){
var url = "getCal.php?startDate=" + startDateNum;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = addCalendar;
xmlHttp.send(null);
}
function addCalendar(){
var divName = "StartDate" + startDateNum + "Div";
var response = xmlHttp.responseText;
if (xmlHttp.readyState == 4){
var calscript = document.createElement("script");
calscript.setAttribute("type", "text/javascript");
calscript.appendChild(document.createTextNode(response));
document.getElementById(divName).appendChild(calscript);
startDateNum++;
}
}

Categories