Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data? - ajax

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},

The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

Related

Column can not be null in ajax laravel update function

Hi guys i am sending my updated values from ajax to my update function.i am getting error as "Column cannot be null"
Here is my input which i am sending json data:
<input type="text" id="jsonData" name="jsonData">
And here is my ajax form:
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#jsonData').val();
var sort_order = $('#sort_order').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log('json',jasondata);
//return false;
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
window.location.href ="/eqtype-editor";
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
and here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
From ajax when i console i am getting my json data..i am getting error as qtype_json cannot be null.
Can anyone help me where i am missing it.
Thanks in advance.
You use a wrong key for your data.
Change the line in your controller:
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
to
$qtype_editor->qtype_json = json_decode($request->input('qtype_json'));
and it will work.

admin-ajax.php do not recognizes 'action'. $_REQUEST is empty

After two days of fruitless research, I decided to join the community. I hope to get a solution. I develop a plug-in that, among other things, must implement the upload of documents. this should be done using ajax technology. the problem is that the request is approved, but admin_ajax.php reacts like no action was taken. Outside of wp this piece of code works fine, as it was thought out. The problems come with installing this code in wp. Below is my code
PHP. This code in the main class that will call from main modul of plugin
class main{
//other activation methods
private function register_scripts(){
add_action('wp_enqueue_scripts', array($this,'re_add_script'));
}
public function re_add_script() {
wp_enqueue_script('re_upload',plugins_url('re'.'/js/re_upload.js'),array('jquery'));
wp_localize_script('re_upload',"re_ajax",array(
'ajaxurl'=>admin_url("admin-ajax.php")));
add_action( 'wp_ajax_upload', 'processingUpload');
}
}//end of class
//callback function
function processingUpload(){
$clsUpload = new UploadsDocs();
$clsUpload->setRequestedData($_FILES,$_POST['doc_id']);
$clsUpload->checkUploadsFiles();
$clsUpload->outputFilesList();
wp_die();
}
jQuery 're_upload.js'
jQuery(document).ready(function (e) {
jQuery('#bt_upload').on('click', function () {
var toUpload=getFileListToUpload();
var form_data = new FormData();
var ins = input.files.length;
for (var x = 0; x < ins; x++) {
if (isFileToUpload(input.files[x],toUpload)){
form_data.append("files[]", input.files[x]);
}
}
form_data.append("doc_id", jQuery('#doc_id')[0].value);
var data_to_sent={
action: 'upload',
datas: form_data
};
jQuery.ajax({
url: re_ajax.ajaxurl, // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: data_to_sent,
type: 'post',
success: function (response) {
// do something
},
error: function (response) {
// do something
},
xhr: function(){
//upload Progress
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
jQuery('#bt_upload').css("display","none");
jQuery('#progress-wrp').css("display","block");
jQuery('#progress-wrp' +" .progress-bar").css("width", + percent +"%");
(percent<50)? jQuery('#progress-status').addClass('status-less-then-50'): jQuery('.status-less-then-50').removeClass('status-less-then-50').addClass('status-more-then-50');
jQuery('#progress-status').text("Uploading..."+percent +"%");
}, true);
}
return xhr;
},
mimeType:"multipart/form-data"
});
});
});
function getFileListToUpload(){
var list=[];
var elem = document.getElementsByClassName('preview');
var tag_li=elem[0].querySelectorAll('p');
for (var i=0;i<tag_li.length;i++){
list[i]=tag_li[i].textContent.split('(')[0];
}
return list;
}
function isFileToUpload(input_file,files_toUpload){
var res=false;
for(var i=0; i<files_toUpload.length;i++){
if (input_file.name==files_toUpload[i]){
res=true;
break;
}
}
return res;
}
The problem is
add_action( 'wp_ajax_upload', 'processingUpload');
is not called.
The upload is done in two separate invocations of the server. The first invocation displays the upload page to the user. The second invocation processes the AJAX request. Your call to
add_action( 'wp_ajax_upload', 'processingUpload');
is done in the first invocation where it is not needed but not in the second invocation where it is needed.
Please read https://codex.wordpress.org/AJAX_in_Plugins. (Observe carefully how the call to 'add_action( 'wp_ajax_...', ...) is done.) Further, you need to read about nonces.
Try to append action to your ajax url like:
url: re_ajax.ajaxurl?action=upload
and
data: form_data
or pass it to form_data like:
form_data.append('action', 'upload')

Can't update a single doc in Mongo with Node

Hopefully someone can point out my error here.
In my app a user clicks on a button to insert a doc into the database. When they click on another button, a timestamp is added to an array.
Here's the code to create the doc (it works):
// Add User
function addUser(event) {
event.preventDefault();
ident = makeWords(2);
var newUser = {
'ident' : ident,
'group': '',
'timestamps': [],
'date_created': Date()
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
if (response.msg === '') {
console.log('user added');
} else {
alert('Error');
}
});
};
And here's the route which handles it:
/*
* POST to adduser.
*/
router.post('/adduser', function(req, res) {
var db = req.db;
var collection = db.get('testcol'); //'testcol' is the name of my collection
collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
I kind of thought that updating a doc would be just as easy. I'm grabbing the doc by the ident field, which will be unique to each user. However, I can't seem to make the client-side stuff pass to the server. Here's my client-side update:
function addError(event) {
event.preventDefault();
// If it is, compile all user info into one object
var errorUpdate = {
'$push': {'error_button': Date()}
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'PUT',
data: errorUpdate,
url: '/users/errorUpdate',
dataType: 'JSON'
}).done(function( response ) {
if (response.msg === '') {
console.log("update sent, didn't receive an error");
}
else {
alert('Error');
}
});
};
This code executes, but the server-side just throws 500s. Here's that function:
/*
* update mongo doc
*/
router.put('/errorUpdate', function(req, res) {
var db = req.db;
var collection = db.get('testcol');
collection.update({'ident': ident},req.body, function(err, result){
if (err) {
console.log('Error updating menu: ' + err);
res.send({'users.js: error':'An error has occurred'});
} else {
console.log('doc has been updated');
res.send(item);
}
});
});
Any idea where I'm going wrong?
I solved this and it was a really really stupid mistake.
You might notice in my server-side code I use a variable called ident:
router.put('/errorUpdate', function(req, res) {
var db = req.db;
var collection = db.get('testcol');
collection.update({'ident': ident},req.body, function(err, result)...
ident is a global variable from my client-side stuff (global.js, which makes the ajax call), and it never made it to the server.
Further, I tried to send the Mongo update statement with the ident variable, which is totally unnecessary and just caused headaches.
Here's how I fixed it. This is client-side (where I only send the ident variable):
function addError(event) {
event.preventDefault();
// If it is, compile all user info into one object
var identifyMe = {
'ident': ident
}
// Use AJAX to post the object to our adduser service
$.ajax({
type: 'POST',
url: '/users/errors',
data: identifyMe,
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
console.log('update sent, no errors received');
}
else {
console.log('Error detected. Response was: ' + response);
}
});
};
... and this is server-side, where I take that identifier and do the update (this works because all I'm doing is inserting a time stamp):
router.post('/errors', function(req, res) {
console.log(req.body);
var identifier = req.body.ident;
var db = req.db;
var collection = db.get('testcol');
collection.update({'ident': identifier}, {$push: {'error_button': Date()}}, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
You might notice that I'm pulling out that ident variable from the JSON that's being passed, with req.body.ident.
Hope this helps someone else struggling with updating a Mongo doc by posting to Express routes via Ajax with Node! :)

How can I handle a ajax request response in the Flux Architecture?

Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.

Node.js modified AJAX insertion to MongoDB

I am succesfully posting an AJAX insert in my MondoDB database.
The user is supposed to fill in 3 fields,
Full Name
Email
Phone
What I would like to do is:
generate a random number in server-side and save it as a 4th field in my MongoDB.
Also I would like to post it as a response back to the user.
Here is my users.js file (server-side)
* POST to adduser.
*/
router.post('/adduser', function(req, res) {
var db = req.db;
var codeResponse = generateCode();
db.collection('userlist').insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '',code: codeResponse } : { msg: err }
);
});
});
function generateCode(){
var code = Math.random() *1000000;
code = Math.floor(code);
return code;
}
And this is my AJAX call(client-side)
var newUser = {
'id2': id2,
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'phone': $('#addUser fieldset input#inputUserPhone').val(),
}
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function( response ) {
// Check for successful (blank) response
if (response.msg === '') {
console.log(response);
}
else {
alert('Error: ' + response.msg);
}
});
Easy enough, add it to your object before insert and post back the object:
router.post('/adduser', function(req, res) {
var db = req.db;
var document = req.body;
var codeResponse = generateCode();
document.code = codeResponse;
db.collection('userlist').insert(document, function(err, result){
if (err) //do something
return;
else
res.send(document);
});
});

Resources