$ is not defined error while attaching the ajax html response? - jquery-ui

Below is the code snippet which is hitting the url on server and getting the html response.I can see
the response inside firefox debugger but it does not display in div tag.
$.ajax({
url: url,
dataType: 'html',
data: '',
type: 'POST',
success: function(data) {
//in firefox debugger i can see complete html response inside data
$('#displayContent').html(data); // but here, it does not
// append the html inside div displayContent. Instead it makes
// the current page blank
}
});​
Looks like this is happening because of " $ is not defined " error(which i see in firefox debugger). This is happening because of inclusion of below javascript file because if i comment out this file i dont get this error in firefox debugger and page gets displayed correctly. But i can not comment out this file because i need it for text rich editor.
I am not getting why i am getting this error though same tiny_mce.js is working in other jsp files? Is there any relation of this with loading the html content thru ajax?
<script type="text/javascript" src='<s:url value="/script/tinymce/jscripts/tiny_mce/tiny_mce.js"/>'></script>

jQuery has a noConflict mode, which will allow you to use a different shortcut for calling jQuery functions and leave '$' for other frameworks.
http://api.jquery.com/jQuery.noConflict/

First of all include jquery in your project and secondly include tinymce like this.
<script type="text/javascript" src="/script/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>

Related

WKWebView - Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin

I trying to read my local JSON file on IOS WKWebview. However Failed to load resource: Origin null is not allowed by Access-Control-Allow-Origin.
I'm using UIWebview before and it's work fine. However when i change to WKWebview this error happen.
$.ajax({
type: 'GET',
url: 'json_app/country_state_json.json?callback=?',
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json)
{},
error: function(e) {}
});
Please assist.
Unfortunately, at this point WKWebView does not handle JavaScript asynchronously loading files using the "file://" protocol [1][2]. It works when the files are loaded from the DOM, just not using ajax or jQuery's .get (which is just abstracted ajax).
Here's a hack that I am simultaneously proud of and not proud of:
I have an app that needs to load a JSON object based on some dynamic information and then process it to display the web content. Originally, I was trying to have the JavaScript get the JSON file dynamically:
The old HTML:
<html>
<head>
<script type="text/javascript" src="makeContent.js"></script>
</head>
<body></body>
</html>
The old JSON:
{
"myData": true,
...
}
The old JavaScript:
$.get("data.json", function (data) {
// Process the data and generate the content
}, "json");
With this, I was encountering the same problem that you were. WKWebView would not load the data.json file.
My hack was to include the JSON content as another JavaScript object that is included in the DOM. The new JavaScript script simply assigns the JSON data as a string into a global variable. Note that this string needs to be a single line, as JavaScript doesn't support multiline strings. Then, this new script is dynamically inserted into the DOM when the WKWebView loads:
JavaScript Data file (replaces the JSON file):
var data = '{ "myData": true, ... }';
Swift:
let jsonInsertion = "var node = document.createElement('script');" +
"node.setAttribute('src', 'data.js');" +
"node.setAttribute('type', 'text/javascript');" +
"var head = document.getElementsByTagName('head')[0];" +
"head.insertBefore(node, head.childNodes[0]);"
webView?.evaluateJavaScript(jsonInsertion, completionHandler: { (_, error) in
print(error)
})
The resulting HTML:
<html>
<head>
<script type="text/javascript" src="data.js"></script>
<script type="text/javascript" src="makeContent.js"></script>
</head>
<body></body>
</html>
Now, your JavaScript should be able to access the data as a global variable, and convert it using JSON.parse(data). You might need to add some synchronization code to ensure that your script runs after the data script is inserted by the app.
Again, this is a hack, but it's working for me. Hopefully it might be useful to you until Apple allows the "file://" protocol.
I bet that you need to provide a full url in the request instead of a relative one. How about using:
url: document.URL + "/json_app/country_state_json.json?callback=",
(I removed the trailing ? - that is not correct and results in a malformed URL)

YouTube API Academy

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

Ad blocker blocks Ajax call response html

I am rendering some stats on my page, as this takes a bit of time I made this request an ajax call after the page loads
<script type ="text/javascript">
$(document).ready(function () {
$.ajax({
url: '#Url.RouteUrl(Routes.MyAds.AjxCallFoAbc, new {advertId = Model.CreateAdvertHeader.SelectedAdvert.Id})',
type: 'GET',
cache: false,
success: function(response) {
$('.advert-performance').replaceWith(response);
}
});
});
</script>
This works perfectly for me, its causing grief when the user installs a ad-blocker, this content is being blocked, I have debugged the code-base and found the ajax call route is never being hit when the ad-blocker is enabled on the browser
What is the work-around for this, I need show the stats even if the ad-blocker is installed
Resolved it
The reason being, my route which the ajax was pointed to had a advert-stats as part of the url, which caused the blocker to block it,
simply changing the route has fixed it

bind a jquery plugin to ajax loaded content

I've used sortable/portlet jquery ui plugin on my website. I load some boxes after the page is loaded via ajax. but they don't look like the boxes appears at the page load time. I know the problem loading via ajax and bind issue. But how can I solve it?
You're ajax call has a success method which you can use to bind to elements that have been dynamically added.
For example you could do
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
$(".column").sortable({ connectWith: ".column", cursor: 'crosshair' });
}
});

ZendX DatePicker issue under Ajax request

I am facing issue while i load a form on ajax request. i followed the steps :
Enable jqueryUi in layout.
creates a form element like :
$dob = new ZendX_JQuery_Form_Element_DatePicker('patient_dob');
$dob->setLabel('')
->addFilter('StripTags')
->addFilter('StringTrim')
//->addValidator('Date')
->setAttrib('readonly', 'true')
->setJQueryParam('dateFormat', 'yy-mm-d')
->setDecorators(array(
'Description', 'Errors', 'UiWidgetElement',
array(array('data' => 'HtmlTag'), array('tag' => 'Div', 'class'=>'calender_input'))
));
and just called the element into form. It is working when page load normally but not with ajax request. What is the reason? any suggestions? i googled a lot about it.
The problem is that the javascript code that activates the date picker is rendered by the ZendX_Jquery extension to happen when the document is ready:
<script type="text/javascript">
//<!--
$(document).ready(function() {
$("#patient_dob").datepicker({});
});
//-->
</script>
which makes sense with non-ajax requests, but never is executed in an ajax request because the document.ready has already happened in the parent's page. You can add your own in your view directly:
<script type="text/javascript">
$("#patient_dob").datepicker({});
</script>
I haven't yet found a solution for this from the Zend Jquery extension, but if you do please let me know!

Resources