jQuery Form plugin submit several forms but wait until previous has ended - jquery-forms-plugin

Users are abled to add new forms which are all submited with one button click and "jQuery Form plugin". To submit each form I iterate over forms which have a certain class.
As the users can submit images and the server has to do some work with each Image I´d like to wait until the previous submit has finished with a success statusText. Currently (I just do a timeout of 2000 which is nothing more than a "hackish" solution.)
I think I can use success function for this but do not know how I connect my submit loop with the returned success statusText. Here is a fiddle.
Here what I have:
var userform = '<form class="myForm" action="up.php" method="post"> ' +
'Name: <input type="text" name="name" />' +
'file: <input type="file" name="img[]" multiple />' +
'Comment: <textarea name="comment"></textarea>' +
'<input type="submit" value="Submit Comment" />' +
'</form>';
function showResponse(responseText, statusText, xhr, form) {
if (statusText === "success") {
console.log("the submit ended with success");
//submit next form should happen
}
}
var options = {
success: showResponse
};
$('#add').click(function() {
$(userform).appendTo('.append').each(function() {
$('.myForm').ajaxForm(options);
});
});
$("#all").click(function() {
var collection = $('.myForm');
if (collection.length > 0) {
var i = 0;
var fn = function() {
var element = $(collection[i]);
$(element).submit().addClass('done').hide("slow");
if (++i < collection.length) {
setTimeout(fn, 2000);
}
};
fn();
}
});
Thanks!

The submit handler simply does a std POST/GET so you aren't going to get a response back. You are going to want to change your code to use ajax and then have the server return a response of success = true/false or whatever you prefer
https://jsfiddle.net/mj9dbLh1/3/
Change this...
var element = $(collection[i]);
$(element).submit().addClass('done').hide("slow");
if (++i < collection.length) {
setTimeout(fn, 2000);
}
To something like...
var element = $(collection[i]);
$(element).addClass('done').hide("slow");
$.post("ajax/test.html", function( data ) {
fn(); // DO SUCCESS ACTION HERE
});
Keep in mind this will execute on each success SO you may want to first get a count of the number of forms (which gives you the number of ajax calls). Then increment that count for each success action. Once you get your total you can Display ALL SUCCESS.
Take a look at these docs for more clues on how to handle errors and what not.
http://api.jquery.com/jquery.post/

Related

Cancel a previous axios request on new request in Vue Js

I am trying to implement a search which loads user data from the backend on every word change using #input and populate in datalist, now for every change a new request is generated while the old request is still processing/pending this causes some problems. I am looking to cancel old request on every new request that will take place.
Html code in vue js
<input type="text" class="form-control" placeholder="Search Name" v-model="forms.name" list="getname" #input="inputData()" required> <datalist id="getInput" > <option v-for="option in options">{{option}}</option> </datalist>
Function to load data
axios.get('Url/GetUser/'+ this.forms.name).then((response) => {if(response.data.error){ this.errorNya = response.data; this.loading2 = false;}else{ this.errorNya.username = ""; this.options = response.data; this.loading2= false; this.disableButton = true; }
I have referred the documentation and other sources for this question, and i found a solution which suited me best.
this.cancelFunc();
//Below line creates a cancel token for this request
let axiosSource = axios.CancelToken.source();
this.request = { cancel: axiosSource.cancel };
//then we pass the token to the request we want to cancel.
axios.get('/Url/GetUser/'+ this.forms.username, {cancelToken: axiosSource.token,}).then((response) => {
if (response.data.error) {
this.errorNya = response.data;
this.loading2 = false;
} else {
this.errorNya.username = "";
this.options = response.data;
this.loading2 = false;
this.disableButton = true;
}
},
cancelFunc() {
if (this.request)
this.request.cancel();
},
i know this will not be the best way to do this, but this solved my problem.

How to show page before executing OnGet?

I have a razor page that shows a 'Please wait' box and the OnGet method does some stuff that might take a few seconds and ends with a LocalRedirect.
The razor code:
#page
#inject IStringLocalizer<Startup> localizer
<div class="login-page">
<div class="login-box">
<div class="card">
<div class="card-body login-card-body">
<div class="help-block text-center">
<div class="spinner-border" role="status" />
</div>
<p class="login-box-msg">#localizer["PleaseWait"]</p>
</div>
</div>
</div>
</div>
And the code-behind:
public async Task<IActionResult> OnGet()
{
//Do some stuff that takes a few seconds...
return LocalRedirect("/Dashboard");
}
Everything is working apart from the page first being shown and then executing the code.
Is it possible to first render the page (so that the users can see that something is happening) and then execute the code in the OnGet?
Move your long async routines from OnGet to a number of named handler methods. Allow the page to render a "please wait" message and use client-side code (jQuery AJAX or plain Fetch) to call the named handlers. Keep track of when they complete and when all have completed, redirect to the other page.
Here's an example where the OnGet simply renders the page (can include a "please wait" message"), and a number of named handlers simulate routines of varying length:
public void OnGet()
{
}
public async Task OnGetTwoSeconds()
{
await Task.Delay(2000);
}
public async Task OnGetThreeSeconds()
{
await Task.Delay(3000);
}
public async Task OnGetFiveSeconds()
{
await Task.Delay(5000);
}
The following script goes in the Razor page itself. It consists of three variables for tracking task completion and a method that redirects to the home page when all three have completed. Each of the named handlers is called by the code and sets its tracking variable to true on completion as well as calling the redirect function:
#section scripts{
<script>
let twosecondsdon = false;
let threesecondsdone = false;
let fivesecondsdone = false;
function redirect(){
if (twosecondsdone && threesecondsdone && fivesecondsdone) {
location.href = '/';
}
}
fetch('?handler=TwoSeconds').then(() => {
twosecondsdone = true;
redirect();
})
fetch('?handler=ThreeSeconds').then(() => {
threesecondsdone = true;
redirect();
})
fetch('?handler=FiveSeconds').then(()=>{
fivesecondsdone = true;
redirect();
})
</script>
}
When all three complete, the redirect function does its thing.
Is it possible to first render the page (so that the users can see
that something is happening) and then execute the code in the OnGet?
Yes you can do that. Currently, I am showing you the delay counter where you can replace your page. Please follow the steps below:
HTML:
Script:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var counter = 5;
(function countDown() {
if (counter-- > 0) {
$('#timer').text("Please wait... we are redirecting you to register page..." + counter + ' s');
setTimeout(countDown, 1000);
} else {
window.location.href = "https://localhost:44361/userlog/ViewCalculateAge";// Here put your controller URL where you would like to redirect
}
})();
});
</script>
}
Output:

Vue JS fire a method based on another method's output unique ID

I'm trying to render a list of notes and in that list I would like to include the note's user name based on the user_id stored in the note's table. I have something like this, but at the moment it is logging an error stating Cannot read property 'user_id' of undefined, which I get why.
My question is, in Vue how can something like this be executed?
Template:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{user.name}}</em>
</div>
Scripts:
methods:{
fetchNotes(id){
return this.$http.get('http://api/notes/' + id )
.then(function(response){
this.notes = response.body;
});
},
fetchUser(id){
return this.$http.get('http://api/user/' + id )
.then(function(response){
this.user = response.body;
});
}
},
created: function(){
this.fetchNotes(this.$route.params.id)
.then( () => {
this.fetchUser(this.note.user_id);
});
}
UPDATE:
I modified my code to look like the below example, and I'm getting better results, but not 100% yet. With this code, it works the first time it renders the view, if I navigate outside this component and then back in, it then fails...same thing if I refresh the page.
The error I am getting is: [Vue warn]: Error in render: "TypeError: Cannot read property 'user_name' of undefined"
Notice the console.log... it the returns the object as expected every time, but as I mentioned if refresh the page or navigate past and then back to this component, I get the error plus the correct log.
Template:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{note.user.user_name}}</em>
</div>
Scripts:
methods:{
fetchNotes(id){
return this.$http.get('http://api/notes/' + id )
.then(function(response){
this.notes = response.body;
for( let i = 0; i < response.body.length; i++ ) {
let uId = response.body[i].user_id,
uNote = this.notes[i];
this.$http.get('http://api/users/' + uId)
.then(function(response){
uNote.user = response.body;
console.log(uNote);
});
}
});
},
}
It looks like you're trying to show the username of each note's associated user, while the username comes from a different data source/endpoint than that of the notes.
One way to do that:
Fetch the notes
Fetch the user info based on each note's user ID
Join the two datasets into the notes array that your view is iterating, exposing a user property on each note object in the array.
Example code:
let _notes;
this.fetchNotes()
.then(notes => this.fetchUsers(notes))
.then(notes => _notes = notes)
.then(users => this.joinUserNotes(users, _notes))
.then(result => this.notes = result);
Your view template would look like this:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{note.user.name}}</em>
</div>
demo w/axios
UPDATE Based on the code you shared with me, it looks like my original demo code (which uses axios) might've misled you into a bug. The axios library returns the HTTP response in a data field, but the vue-resource library you use returns the HTTP response in a body field. Attempting to copy my demo code without updating to use the correct field would cause the null errors you were seeing.
When I commented that axios made no difference here, I was referring to the logic shown in the example code above, which would apply to either library, given the field names are abstracted in the fetchNotes() and fetchUsers().
Here's the updated demo: demo w/vue-resource.
Specifically, you should update your code as indicated in this snippet:
fetchInvoices(id) {
return this.$http.get('http://localhost/php-api/public/api/invoices/' + id)
// .then(invoices => invoices.data); // DON'T DO THIS!
.then(invoices => invoices.body); // DO THIS: `.data` should be `.body`
},
fetchCustomers(invoices) {
// ...
return Promise.all(
uCustIds.map(id => this.$http.get('http://localhost/php-api/public/api/customers/' + id))
)
// .then(customers => customers.map(customer => customer.data)); // DON'T DO THIS!
.then(customers => customers.map(customer => customer.body)); // DO THIS: `.data` should be `.body`
},
Tony,
Thank you for all your help and effort dude! Ultimately, with the help from someone in the Vue forum, this worked for me. In addition I wanted to learn how to add additional http requests besides the just the user in the fetchNotes method - in this example also the image request. And this works for me.
Template:
<div v-if="notes.length > 0">
<div v-if="loaded === true">
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{note.user.user_name}}</em>
<img :src="note.image.url" />
</div>
</div>
<div v-else>Something....</div>
</div>
<div v-else>Something....</div>
Script:
name: 'invoices',
data () {
return {
invoices: [],
loaded: false,
}
},
methods: {
fetchNotes: async function (id){
try{
let notes = (await this.$http.get('http://api/notes/' + id )).body
for (let i = 0; notes.length; i++) {
notes[i].user = (await this.$http.get('http://api/user/' + notes[i].user_id)).body
notes[i].image = (await this.$http.get('http://api/image/' + notes[i].image_id)).body
}
this.notes = this.notes.concat(notes)
}catch (error) {
}finally{
this.loaded = true;
}
}

Can we implement On key up filter option in Yii's cGridview?

I am currently trying to implement automatic filtering in Yii cGridview, By default it filters 'onclick', or 'enter' key press, But I need to change that event to "onkeyup"|
my code is like this
Yii::app()->clientScript->registerScript('search',"
$('.filters > td >input').keyup(function(){
$('#grid-id').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
when I entered the first letter filtering occured, but after filtering and rendering the code fails.. please give me a solution.. Is there any php yii gridview extension which has filtering onkeyup
You need to change the way you attach the keyup listeners. After the gridview refreshed through AJAX, all elements inside the grid are replaced. So there's no keyup attached anymore. You can try something like:
$('body').on('keyup','.filters > td > input', function() {
$('#grid-id').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
#Michael Härtl's answer is right. But 2 Problem occur when you use this code.
1) When User Search in filter at that time, every time grid will be refresh so focus of input box will be lost.
2) When you search in one filter input and if you go to second input field field at that time first input box will be lost.
So now I have got the solution for that.
Set this java script code on your grid view.
Yii::app()->clientScript->registerScript('search', "
$('body').on('keyup','.filters > td > input', function() {
$(document).data('GridId-lastFocused',this.name);
data = $('#GridId input').serialize();
$('#GridId').yiiGridView('update', {
data: data
});
return false;
});
// Configure all GridViews in the page
$(function(){
setupGridView();
});
// Setup the filter(s) controls
function setupGridView(grid)
{
if(grid==null)
grid = '.grid-view tr.filters';
// Default handler for filter change event
$('input,select', grid).change(function() {
var grid = $(this).closest('.grid-view');
$(document).data(grid.attr('id')+'-lastFocused', this.name);
});
}
// Default handler for beforeAjaxUpdate event
function afterAjaxUpdate(id, options)
{
var grid = $('#'+id);
var lf = $(document).data(grid.attr('id')+'-lastFocused');
// If the function was not activated
if(lf == null) return;
// Get the control
fe = $('[name=\"'+lf+'\"]', grid);
// If the control exists..
if(fe!=null)
{
if(fe.get(0).tagName == 'INPUT' && fe.attr('type') == 'text')
// Focus and place the cursor at the end
fe.cursorEnd();
else
// Just focus
fe.focus();
}
// Setup the new filter controls
setupGridView(grid);
}
// Place the cursor at the end of the text field
jQuery.fn.cursorEnd = function()
{
return this.each(function(){
if(this.setSelectionRange)
{
this.focus();
this.setSelectionRange(this.value.length,this.value.length);
}
else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', this.value.length);
range.moveStart('character', this.value.length);
range.select();
}
return false;
});
}");
Add this line to your gridview widget code.
'afterAjaxUpdate'=>'afterAjaxUpdate',
For example:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'GridId',
'afterAjaxUpdate'=>'afterAjaxUpdate',
));

Dojo Tooltip only shows after first mousover event

I'm using dojo's event delegation to connect a Tooltip widget to dynamically generated dom nodes.
The Dojo site explains event delegation this way:
"The idea behind event delegation is that instead of attaching a
listener to an event on each individual node of interest, you attach a
single listener to a node at a higher level, which will check the
target of events it catches to see whether they bubbled from an actual
node of interest; if so, the handler's logic will be performed."
Following is my code implementation. It works beautifully ... EXCEPT, the tooltip only shows AFTER the first mouse over event. When I first mouseover the node, the event fires perfectly, but the tooltip doesn't render. It will only show the consequent mouseover events. On the first mouseover event, I can watch the Firebug console and see the xhr.get go to the database and get the correct data. If I comment out the tooltip and throw in a simple alert(), it works the first time.
Any suggestions on how to get the Tooltip to show on the first mouseover event? Thanks in advance!
<div class="col_section" id="my_groups">
<div class="col_section_label">My Groups</div>
<ul>
<?php
foreach($myGroups as $grp) {
echo '<li><a class="myGroupLink" id="grp'.$grp['grp_id'].'">'.$grp['name'].'</a></li>';
}
?>
</ul>
</div>
<script>
require(["dojo/on",
"dojo/dom",
"dijit/Tooltip",
"dojo/_base/xhr",
"ready!"], function(on, dom, Tooltip, xhr) {
// Get Group ToolTip
var myObject = {
id: "myObject",
onMouseover: function(evt){
var grp_id = this.id;
var content = '';
xhr.get({
url: "getGrpInfo.php",
handleAs: "json",
content: {
grp_id: grp_id,
content: "tooltip"
},
load: function(info) {
if(info == 0) {
content = '<div class="grpToolTip">';
content += ' Information about this group is confidential';
content += '</div>';
} else {
content = '<div class="grpToolTip">';
content += ' <img src="../ajax/getimg.php?id='+info.logo_id+'" />';
content += ' <div style="text-align:center">'+info.name+'</div>';
content += '</div>';
}
new Tooltip({
connectId: [grp_id],
label: content
});
},
error: function() {}
});
}
};
var div = dom.byId("my_groups");
on(div,".myGroupLink:mouseover",myObject.onMouseover);
});
</script>
Your Tooltip does not show on the first onmouseover because it does not exist at the moment the onmouseover event was fired.
dijit/Tooltip instances manage theirs mouse events themselves, so you do not have to manage onmouseover/onmouseout and you probably did so because you do not want to preload data or you want to load data every time the tooltip is about to show.
Beside dijit/Tooltip instances you can use Tooltip.show(innerHTML, aroundNode, position) and Tooltip.hide(aroundNode) to display tooltips, but in that case you will have to manage mouse events yourself, which is what you need, because from the UX perspective, you do not want to show single tooltip, you want to:
Show a tooltip indicating information is being loaded.
Then either:
display XHR loaded information if a user still hover over the node
cancel XHR and hide tooltip on mouseout
Here is working example: http://jsfiddle.net/phusick/3hmds/
require([
"dojo/dom",
"dojo/on",
"dojo/_base/xhr",
"dijit/Tooltip",
"dojo/domReady!"
], function(
dom,
on,
xhr,
Tooltip
) {
on(dom.byId("groups"), ".group-link:mouseover", function(e) {
var target = e.target;
Tooltip.show("Loading...", target);
var def = xhr.post({
url: "/echo/html/",
content: { html: target.textContent},
failOk: true,
load: function(data) {
Tooltip._masterTT.xhr = null;
Tooltip._masterTT.containerNode.innerHTML = data;
Tooltip._masterTT.domNode.width = "auto";
},
error: function(e) {
if (e.dojoType != "cancel") {
console.error(e);
}
}
});
Tooltip._masterTT.xhr = def;
});
on(dom.byId("groups"), ".group-link:mouseout", function(e) {
var target = e.target;
Tooltip.hide(target);
if (Tooltip._masterTT.xhr) {
Tooltip._masterTT.xhr.cancel();
}
});
});​
As usual, I was over-thinking the problem, focusing on event registration rather than on simply creating the tooltips when the page loads. So, it's really stupidly simple:
query for the nodes
iterate through them and create the tooltips pointing to each node.
var myGroupsList = query("a.myGroupLink"); // query nodes based on class
array.forEach(myGroupsList,function(entry,i){ // iterate through
var grp_id = entry.id;
var content = '';
xhr.get({ // get data via xhr.get
url: "getGrpInfo.php",
handleAs: "json",
content: {
grp_id: grp_id,
content: "tooltip"
},
load: function(info) {
if(info == 0) {
content = '<div class="grpToolTip">';
content += ' Information about this group is confidential';
content += '</div>';
} else {
content = '<div class="grpToolTip">';
content += ' <img src="../ajax/getimg.php?id='+info.logo_id+'" />';
content += ' <div style="text-align:center">'+info.name+'</div>';
content += '</div>';
}
new Tooltip({ // create tooltip
connectId: [entry.id],
label: content
});
},
error: function() {}
});
});