Why doesn't javascript execute in .php file loaded with Ext.Ajax.Request? - ajax

I want to load .php files via ajax which execute ExtJS script as they load, which in turn modifies the existing ExtJS objects already present in the DOM.
However, I can't even get Javascript to execute from a page that is being loaded via Ext.Ajax.request. And no errors are showing up in the Firebug Net panel. The PHP code gets executed, but not the Javascript. When I call the page being loaded by itself in the browser, it executes the Javascript fine.
How can I get Javascript to execute in pages loaded with Ext.Ajax.request?
Ext.onReady(function(){
var menuItemStart = new Ext.Panel({
id: 'panelStart',
title: 'Start',
html: 'This is the start menu item.',
cls:'menuItem'
});
var menuItemApplication = new Ext.Panel({
id: 'panelApplication',
title: 'Application',
html: 'this is the application page',
cls:'menuItem'
});
var regionMenu = new Ext.Panel({
region:'west',
split:true,
width: 210,
layout:'accordion',
layoutConfig:{
animate:true
},
items: [ menuItemStart, menuItemApplication ]
});
var regionContent = new Ext.Panel({
id: 'contentArea',
region: 'center',
padding:'10',
autoScroll: true,
html: 'this is the content'
});
new Ext.Viewport({
layout: 'border',
items: [ regionMenu, regionContent ]
});
menuItemStart.header.on('click', function() {
Ext.Ajax.request({
url: 'content/view_start.php',
success: function(objServerResponse) {
regionContent.update(objServerResponse.responseText);
}
});
});
menuItemApplication.header.on('click', function() {
Ext.Ajax.request({
url: 'content/view_application.php',
success: function(objServerResponse) {
regionContent.update(objServerResponse.responseText);
}
});
});
});
the file that is being loaded via Ajax:
<script type="text/javascript">
window.onload=function() {
alert('from application view'); //is not executed
}
//Ext.onReady(function(){
// alert('from application view extjs'); //is not executed
//}
</script>
<?php
echo 'this is the application view at ' . date('Y-m-d h:i:s');
?>

When you get the ajax response the onload event on the window has been already fired so the function won't be executed because the onload event won't be fired again. Try only with the alert:
<script type="text/javascript">
alert('from application view');
</script>
<?php
echo 'this is the application view at ' . date('Y-m-d h:i:s');
?>
UPDATE
Browsers don't execute injected scripts in that way so you can try with something like:
var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
while(scripts=scriptsFinder.exec(responseText))
{
eval(scripts[1]);
}

Have you tried passing true for the second param to Panel.load (which happens to be the loadScripts option)?
regionContent.update(objServerResponse.responseText, true);

Normally, when you call update with ext you just do
update(string,true) and it will execute scripts contained within the string. However, ext core seems to lack this functionality, but there is no documentation for the update method (I had to search the actual code to confirm this.)
If you are using some regular EXT (like ext-all) you can simply add
regionContent.update(objServerResponse.responseText,true);
like this and it should eval the scripts. No dice for me, though - ext-all is too slow but I need eval functionality. I may have to hack EXT.

Related

https.post.promise “.then” not called

Hello – I hope someone could provide some advise or feedback.
Summary: I am trying to create a custom button (UE script) on Sales Order record. That custom button executes a function from a client side script. The function (snippet below) uses https.post.promise. It calls a Suitelet that I will be using to process some backend logic.
Problem: The “.then” portion is not called/executed.
Notes:
Everything is working expect for .then part. The suitelet is called by the post
When I tried to call the same function on pageInit, the .then part is executing
I have used chrome’s javascript profiler as well and tried to compare both executions (by clicking button and pageInit). I can see that .then is being called when the snippet is executed via pageInit but is not executed, when clicking the button
function createIntercoPo(soId){
log.debug('CS - Create Interco PO', 'START ' + soId);
var suiteletURL = url.resolveScript({
scriptId: 'customscript_swx_sl_auto_ic_so_po',
deploymentId: 'customdeploy_swx_sl_auto_ic_so_po',
});
log.debug('CS - Suitelet URL', suiteletURL);
/*https.post({
async: true,
url: suiteletURL,
body: {
soId: soId
},
callback: function(response) {
var result = JSON.parse(response.body);
redirectAfterProcess(result, transId, transType, "generation");
}
});*/
https.post.promise({
url: suiteletURL,
body: {
soId: soId
}
})
.then(function (response){
log.debug({
title: 'Response',
details: response
});
//redirectAfterProcess(soId);
log.debug('CS - Inside Promise', 'Test');
})
.catch(function onRejected(reason) {
log.debug({
title: 'Invalid Request: ',
details: reason
});
});
log.debug('CS - Create Interco PO', 'END');
}

Reload jQgrid on Bootbox closing

I have jQGrid v4.6.0 (I can reproduce the same issue with Free jqGrid) on my page which I can reload using:
$('#jqGrid').trigger('reloadGrid');
It loads data by posting to a server. It posts correctly, gets the returned data correctly, and shows the correct data in the grid.
On the same page I have a link which opens a Bootbox dialog. Calling reloadGrid from within a Bootbox callback seems to make $('#jqGrid').jqGrid "not a function"
bootBoxWindow = bootbox.dialog({
title: "title",
message: "foo",
size: "large",
closeButton: false,
buttons: {
ok: {
label: "Save 2",
className: "btn-success",
callback: function () {
$('#jqGrid').trigger('reloadGrid');
}
}
}
});
When this calls reloadGrid, jqGrid properly posts to my server and retrieves the latest data. However, inside the loadComplete event I can no longer refer to jQuery("#jqGrid").jqGrid.
Example:
jQuery("#jqGrid").jqGrid('showCol', 3);
... calling this inside loadComplete gives error: TypeError: jQuery("#jqGrid").jqGrid is not a function"
I get the same error when using $(this) instead of jQuery("#jqGrid").
I cannot reproduce the issue without Bootbox. If I load the grid, then use this:
setTimeout(function () {
$('#jqGrid').trigger('reloadGrid', [{ current: true }]);
}, 10000);
... there is no error.
The first that I think is that the modal function is outside the jqGrid scope.
Example:
(function($) {
$(function() {
....
var $grid = $("#grid").jqGrid({...});
.....
console.log($grid);
});
})(jQuery);
console.log($grid);
The first console.log will output grid object, the second will throw error.
You may want to look at this article

Instagram API with more than 20 images

I wanted to ask you, if there is any possibility to get more than 20 full-res images from Instagram, using the API.
<script type="text/javascript">
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
});
feed.run();
Thank you in advance, Laurenz Strauch
It may be caused by pagination.
Add
<button id="load-more">
Load more
</button>
to your html. Every time you click on the button, feed.next() will be called and fetches more images if they exist.
<script type="text/javascript">
var loadButton = document.getElementById('load-more');
var feed = new Instafeed({
get: 'user',
userId: '2201292293',
clientId: 'MY_CLIENT_ID',
accessToken:`'MY_ACCESS_TOKEN',
limit: '364',
sortBy: 'most-liked',
template: '<img src="{{image}}">{{likes}}',
resolution: 'standard_resolution'
// every time we load more, run this function
after: function() {
// disable button if no more results to load
if (!this.hasNext()) {
loadButton.setAttribute('disabled', 'disabled');
}
},
});
// bind the load more button
loadButton.addEventListener('click', function() {
feed.next();
});
// run our feed!
feed.run();
</script>
Try this code.

Running into Error while waiting for Protractor to sync with the page with basic protractor test

describe('my homepage', function() {
var ptor = protractor.getInstance();
beforeEach(function(){
// ptor.ignoreSynchronization = true;
ptor.get('http://localhost/myApp/home.html');
// ptor.sleep(5000);
})
describe('login', function(){
var email = element.all(protractor.By.id('email'))
, pass = ptor.findElement(protractor.By.id('password'))
, loginBtn = ptor.findElement(protractor.By.css('#login button'))
;
it('should input and login', function(){
// email.then(function(obj){
// console.log('email', obj)
// })
email.sendKeys('josephine#hotmail.com');
pass.sendKeys('shakalakabam');
loginBtn.click();
})
})
});
the above code returns
Error: Error while waiting for Protractor to sync with the page: {}
and I have no idea why this is, ptor load the page correctly, it seem to be the selection of the elements that fails.
TO SSHMSH:
Thanks, your almost right, and gave me the right philosophy, so the key is to ptor.sleep(3000) to have each page wait til ptor is in sync with the project.
I got the same error message (Angular 1.2.13). My tests were kicked off too early and Protractor didn't seem to wait for Angular to load.
It appeared that I had misconfigured the protractor config file. When the ng-app directive is not defined on the BODY-element, but on a descendant, you have to adjust the rootElement property in your protractor config file to the selector that defines your angular root element, for example:
// protractor-conf.js
rootElement: '.my-app',
when your HTML is:
<div ng-app="myApp" class="my-app">
I'm using ChromeDriver and the above error usually occurs for the first test. I've managed to get around it like this:
ptor.ignoreSynchronization = true;
ptor.get(targetUrl);
ptor.wait(
function() {
return ptor.driver.getCurrentUrl().then(
function(url) {
return targetUrl == url;
});
}, 2000, 'It\'s taking too long to load ' + targetUrl + '!'
);
Essentially you are waiting for the current URL of the browser to become what you've asked for and allow 2s for this to happen.
You probably want to switch the ignoreSynchronization = false afterwards, possibly wrapping it in a ptor.wait(...). Just wondering, would uncommenting the ptor.sleep(5000); not help?
EDIT:
After some experience with Promise/Deferred I've realised the correct way of doing this would be:
loginBtn.click().then(function () {
ptor.getCurrentUrl(targetUrl).then(function (newURL){
expect(newURL).toBe(whatItShouldBe);
});
});
Please note that if you are changing the URL (that is, moving away from the current AngularJS activated page to another, implying the AngularJS library needs to reload and init) than, at least in my experience, there's no way of avoiding the ptor.sleep(...) call. The above will only work if you are staying on the same Angular page, but changing the part of URL after the hashtag.
In my case, I encountered the error with the following code:
describe("application", function() {
it("should set the title", function() {
browser.getTitle().then(function(title) {
expect(title).toEqual("Welcome");
});
});
});
Fixed it by doing this:
describe("application", function() {
it("should set the title", function() {
browser.get("#/home").then(function() {
return browser.getTitle();
}).then(function(title) {
expect(title).toEqual("Welcome");
});
});
});
In other words, I was forgetting to navigate to the page I wanted to test, so Protractor was having trouble finding Angular. D'oh!
The rootElement param of the exports.config object defined in your protractor configuration file must match the element containing your ng-app directive. This doesn't have to be uniquely identifying the element -- 'div' suffices if the directive is in a div, as in my case.
From referenceConf.js:
// Selector for the element housing the angular app - this defaults to
// body, but is necessary if ng-app is on a descendant of <body>
rootElement: 'div',
I got started with Protractor by watching the otherwise excellent egghead.io lecture, where he uses a condensed exports.config. Since rootElement defaults to body, there is no hint as to what is wrong with your configuration if you don't start with a copy of the provided reference configuration, and even then the
Error while waiting for Protractor to sync with the page: {}
message doesn't give much of a clue.
I had to switch from doing this:
describe('navigation', function(){
browser.get('');
var navbar = element(by.css('#nav'));
it('should have a link to home in the navbar', function(){
//validate
});
it('should have a link to search in the navbar', function(){
//validate
});
});
to doing this:
describe('navigation', function(){
beforeEach(function(){
browser.get('');
});
var navbar = element(by.css('#nav'));
it('should have a link to home in the navbar', function(){
//validate
});
it('should have a link to search in the navbar', function(){
//validate
});
});
the key diff being:
beforeEach(function(){
browser.get('');
});
hope this may help someone.
I was getting this error:
Failed: Error while waiting for Protractor to sync with the page: "window.angular is undefined. This could be either because this is a non-angular page or because your test involves client-side navigation, which can interfere with Protractor's bootstrapping. See http://git.io/v4gXM for details"
The solution was to call page.navigateTo() before page.getTitle().
Before:
import { AppPage } from './app.po';
describe('App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should have the correct title', () => {
expect(page.getTitle()).toEqual('...');
})
});
After:
import { AppPage } from './app.po';
describe('App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
page.navigateTo();
});
it('should have the correct title', () => {
expect(page.getTitle()).toEqual('...');
})
});
If you are using
browser.restart()
in your spec some times, it throws the same error.
Try to use
await browser.restart()

Ajax Upload using valums ajax upload plugin inside a form

i just came across this ajax upload plugin and i wish to use it inside a form as shown in the demo page example 3. For some reason i am not able to make it work. I am not sure what parameters come into the function. For example here is my sample code.
$(document).ready(function(){
var upload = new AjaxUpload('property_i',
{
action: 'submitproperty.php',
autoSubmit: false,
onSubmit : function(file , extension){
return false;
}
});
var upload_data = upload.setData({
'propertytype':'propertytype'
});
});
Now the ID used in the AjaxUpload function should be ID of the or of the Entire form. Also how do i use setData method. Any suggestions or links will be very helpful. Thanks
I got it to work with the following code:
new AjaxUpload('#uploader_button', {
action: 'filename.ashx',
autoSubmit: true,
onSubmit: function(file, ext) {
// --- stuff here
// --- add postdata parameters
this.setData({ id: 1, title: docTitle.val() });
},
onComplete: function(file, response) {
// --- stuff here too
}
});
it doesn't utilize the var but instead adds the custom data params in the onSubmit block. The only other difference is that I haven't wrapped the parameter key in quotes as it seems to serialize correctly. And I'm not using autoSubmit: false , but instead it's true...
The only way I could get this to work with autoSubmit: false is to add this outside any function:
var uploader;
var uploadFile;
then in the AjaxUpload(...
onChange: function(file, response){
uploader = this;
uploadFile = file;
},
then in the function to do the upload:
uploader.setData({session: session});
uploader.submit();
Hope this helps
I'm using uploadify and very useful.
http://www.uploadify.com/

Resources