Why is my ExtJS form not submitting? - javascript

I'm using ExtJS to pop up a window with a simple edit form, but on pressing the submit button, no XHR call is made and I get a this.form.el.dom is undefined error reported in the console.
Here's my code:
var myNameSpace = new function(){
var editForm, editWindow;
this.init = function(){
Ext.Ajax.request({
url: '/server/action.php',
success: function(result){
console.log('ajax is working ok'); // I get this
}
});
editForm = new Ext.form.FormPanel({
width:450,
autoHeight: true,
header : false,
items: [{
name: 'color',
fieldLabel: 'Color',
xtype: 'textfield',
value: 'blue'
}],
buttons: [{
text:"Submit",
scope: this, // tried without this, too
handler: function(){
// editForm.getForm().getValues() returns normal values
editForm.getForm().submit({
url: '/server/action.php',
success: function(form, action) {
console.log('Yes! Success!'); // I don't get this
},
failure: function(form, action) {
console.log('failed.'); // I don't get this
}
});
editWindow.close(); // works
console.log('the form is now closed'); // I get this
}
}]
});
editWindow = new Ext.Window(
{
title:'Enter your color',
autoWidth: true,
autoHeight: true,
layout: 'fit',
modal: true,
items: editForm,
closeAction: 'hide'
});
editWindow.show();
};
};
Ext.onReady(function () {
myNameSpace.init();
});
Any light on the subject will be greatly appreciated and profusely upvoted.

I am going to say that the issue is asynchonous nature of form submital. You form closes before the response is received from the Ajax submit event. Try moving your editWindow.close() line inside the success processing block.

Related

Triggering event on clicking OK button in Jquery Modal dialog box

I am trying to display a dialog box with just an OK button on response of an ajax call. When the user clicks OK, it should reload the page. But now page reload is immediately happening after the dialog box is popped up. It is not waiting for the user to click OK. FYI I am using Jquery Modal dialog box.
Simple browser alert() does the job for me, but I don't like the appearance of alert().
Any help is highly appreciated!
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({type: 'alert', title: 'Alert', text: data});
window.location.href = window.location.href;
}
});
Reference:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
// alert(data);
modal({
type: 'alert',
title: 'Alert',
text: data,
buttons: [{
text: 'OK', //Button Text
val: 'ok', //Button Value
eKey: true, //Enter Keypress
addClass: 'btn-light-blue btn-square', //Button Classes
onClick: function() {
window.location.href = window.location.href;
}
}, ],
center: true, //Center Modal Box?
autoclose: false, //Auto Close Modal Box?
callback: null, //Callback Function after close Modal (ex: function(result){alert(result);})
onShow: function(r) {
console.log(r);
}, //After show Modal function
closeClick: true, //Close Modal on click near the box
closable: true, //If Modal is closable
theme: 'xenon', //Modal Custom Theme
animate: true, //Slide animation
background: 'rgba(0,0,0,0.35)', //Background Color, it can be null
zIndex: 1050, //z-index
buttonText: {
ok: 'OK',
yes: 'Yes',
cancel: 'Cancel'
},
template: '<div class="modal-box"><div class="modal-inner"><div class="modal-title"><a class="modal-close-btn"></a></div><div class="modal-text"></div><div class="modal-buttons"></div></div></div>',
_classes: {
box: '.modal-box',
boxInner: ".modal-inner",
title: '.modal-title',
content: '.modal-text',
buttons: '.modal-buttons',
closebtn: '.modal-close-btn'
}
});
}
});
Because your reload runs irrespectively of what is clicked. If you want to assign a callback function to the modal window:
jQuery UI dialog with boolean return - true or false
Also, there is no need to make location.href equal itself (or use the window object). location.reload() works just as well.
You can pass the dialog modal buttons attributes, each with a registered event, like this:
$.ajax({
url: "modules/mymod/save.php",
type: "POST",
data: $('#requestForm').serialize(),
statusCode: {404: function () {alert('page not found');}},
success: function (data) {
$("#dialog-confirm").dialog({
resizable: false,
height: 200,
modal: true,
buttons: {
Proceed: function() {
window.location.href = window.location.href;
},
Cancel: function() {
// Cancellation code here
}
}
});
}
});
Simple browser alert() does the job for me because alert() is an blocking call. If you omit the alert then your code is not bind with any event to check whether user clicked on a button or not, that's why the code block executes immediately and page reloads.
So bind the following code:
window.location.href = window.location.href;
inside some button click, to resolve the issue.
dont use window.location function in success.instead open the modal with ok button at success(how to do that, I think you know already) and assign some id to that button let say id="loction_btn".
then use just this
$('document').on('click','#location_btn',function(){
window.location.href = window.location.href;
});

How can i put ajax in confirm button?

Hi friends i am trying to put ajax url in confirm button to update something in Database.
So i do this in JavaScript Section
function freeze_account() {
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}
and this is code for update
$manager_id = $_POST['manager_id'];
$state = '0';
$update=runQuery("UPDATE `users` SET `userStatus` =:userS WHERE `userID`=:user_id");
$update->bindparam(":userS",$state);
$update->bindparam(":user_id",$manager_id);
$update->execute();
My problem is when i press confirm button ajax works and go to another page but nothing happen in database.
What is wrong in my code Or Maybe I miss something?
any help any idea i will be grateful
Best Regards
look how i solved my problem
Maybe one benefit of my code
Thanks for every one suggestions or helping me
function freeze_account() {
var pid = $('#manager_id').val();
bootbox.dialog({
message: "Are you sure you want to Freeze this account ?",
title: "<i class='glyphicon glyphicon-trash'></i> Freeze !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Freeze!",
className: "btn-danger",
callback: function() {
$.post('update_freeze.php', { 'pid':pid })
.done(function(response){
bootbox.alert(response);
location.reload();
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
}
}
}
});
}
You need to set up an event listener on your button. Firstly, ensure you have an ID on your button so we can grab it.
Now, we create the event listener:
$("#button").on("click", freeze_account());
And, now when you click the button the ajax call should go through successfully.
However, it will still redirect yo due to its default behaviour.
To override this, simply prevent the default event:
function freeze_account(event) {
event.preventDefault(); // stops the button redirecting
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}

Strange behavior of jquery.hotkeys

Although the subject of keyboard shortcuts has been treated here often, I cannot account for the following.
1) I put up a jQuery dialog
function statements ()
{
/* Initialization */
$.ajax
({
url: '/comeAndGo/MOVEMENTS/statements.php',
type: "GET",
dataType: 'html',
async: false,
success: function (data) { $('#mainContainer').html(data); },
error: function () { alert("Error"); }
});
$("#DLG_Statements").dialog(
{
title:"Statements",
height: 560, width: 600,
modal: true,
position: {my: "top", at: "top+60"},
buttons:
[
{
id: "bCancel",
text: "Dismiss",
click: function ()
{
$(this).dialog("close");
location.href = gPath + "homePage.php";
}
},
{
id: "bOK",
text: "OK",
click: function () {}
}
],
draggable: false,
closeOnEscape: false, // (5)
resizable: false
});
$(document).bind('keydown', 'Alt+j', function () { alert ('jquery.hotkeys'); });
}
2) The DLG_Statements is within a <div> inside a form which is part of statements.php. It includes several input elements such as radio buttons, drop-down menus, text input, a check-box.
MY PROBLEM
1) The jquery.hotkeys call does not respond when the cursor is positioned inside certain div's such as a text input field;
2) The jquery.hotkeys call responds unpredictably (it does/it does not) as a consequence of my clicking in different zones of the dialog;
3) The jquery.hotkeys call does not respond at all if I try and be more specific as to the jQuery wrapper, e.g. $("#DLG_Statements").bind (etc.)
What is it I am doing wrong?

Kendo UI, datagrid inserted row produces request multiple times

i have problem with Kendo data grid component.
I'm trying to add new row into grid and create remote request to API via create event.
Problem is that if i try to add new row after first request Kendo make 2 requests instead of the one.
I tried to find some solution for this using transport create and options.success method but without luck.
http://docs.telerik.com/kendo-ui/api/framework/datasource#configuration-transport.create
Could somebody tell to me what i'm doing wrong?
Thanks for any help.
Here is the code of the server response for create:
+ Response 200 (application/json)
{
"status": "OK",
"result":[
{
"id":22,
"username":"blahblah",
"name":"Thomas",
"surname":"Man",
"email":"to.mas.marny#gmail.com",
"created":"1399986964",
"role":"USER"
}
]
}
Here is the code of the method:
$scope.initGrid = function () {
// get access token from localstorage
var token = localStorage
.getItem($rootScope.lsTokenNameSpace);
// set pagination data
var paginationData = {
"token": token,
"data": {
"page": 1,
"items_per_page": 20
}
};
var dataPacket;
dataPacket = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: $rootScope.apiBaseUrl + "user/list",
dataType: "json",
type: "POST",
data: JSON
.stringify(paginationData),
success: function (
response) {
console
.log("List of users succesfully obtained");
console
.log(response.result);
// pass response to
// model
options
.success(response);
// $notification.enableHtml5Mode();
},
error: function (error) {
console
.log("user list request error");
console.log(error);
$notification
.error(
"User list cannot be loaded",
"Please try again in a minute.");
}
});
},
update: function (options) {
console.log("Update");
options
.success("{\"test\":\"test\"}");
},
destroy: function (options) {
console.log("destroy");
options
.success("{\"test\":\"test\"}");
},
create: function (options) {
console.log("Create");
console.log(options.data);
$.ajax({
url: $rootScope.apiBaseUrl + "user/create",
dataType: "json",
type: "POST",
data: JSON
.stringify(options.data),
success: function (
response) {
console
.log("New user created");
console
.log(response.status);
// pass response to
// model
options
.success(response.result);
// $notification.enableHtml5Mode();
},
error: function (error) {
console.log("user list request error");
console.log(error);
$notification
.error(
"User cannot be created",
"Please try again in a minute.");
}
});
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
//batch : true,
//autoSync: true,
schema: {
data: "result",
model: {
id: "id",
fields: {
id: {
editable: false,
nullable: true
},
name: {
editable: true,
nullable: false
},
username: {
editable: true,
nullable: false
}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataPacket,
filterable: true,
pageSize: 20,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: ["id", "name", "username", {
command: ["edit", "destroy"],
title: " ",
width: "200px"
}],
editable: "inline"
});
};
If you declare id inside model then you don't have to declare id inside model fields.
Also when you point
data: "result"
for the model you have to pass
options.success(response)
inside ajax's success function, not just
options.success(response.result)
I think if null is passed to the Datasource of the kendo Grid in the html helper, the Grid will be built in “remote data mode” rather than “local data mode”
and since the read Url is not set the current browser Url will be used for the read operation.
make sure to initialize the list in the Model before using it as a Datasource.

jquery noty on close goto a url

i'm using the jquery noty plugin and when someone clicks the popup, i want it to goto a URL (below) but i cant figure this out... can someone give me a quick fix.. ?
URL i want it to goto: script.php?hidenoty=true
<script type="text/javascript">
function generate(layout) {
var n = noty({
text: "<?php echo $motd?>",
type: 'warning',
dismissQueue: true,
layout: layout,
theme: 'defaultTheme',
animation: {
open: {height: 'toggle'},
close: {height: 'toggle'},
easing: 'swing',
speed: 500 // opening & closing animation speed
},
timeout: false, // delay for closing event. Set false for sticky notifications
force: false, // adds notification to the beginning of queue when set to true
modal: false,
maxVisible: 3, // you can set max visible notification for dismissQueue true option
closeWith: ['click'], // ['click', 'button', 'hover']
callback: {
onShow: function() {},
afterShow: function() {},
onClose: function() {
$.ajax({ url: 'script.php?hidenoty=true' });
},
afterClose: function() {}
},
buttons: false // an array of buttons
});
console.log('html: '+n.options.id);
}
function generateAll() {
generate('topCenter');
}
$(document).ready(function() {
generateAll();
});
</script>
Change this line...
$.ajax({ url: 'script.php?hidenoty=true' });
to this...
window.location.href = 'script.php?hidenoty=true';
ajax is used specifically to load something without changing the page, so the opposite of what you want :)

Categories

Resources