FormData only run once when using ajax
i have a code like this
function SaveFolderThumbnail(folderInfo) {
var formData = new FormData();
if (uploadFile != null || uploadFile != undefined) {
formData.append(uploadFile.name, uploadFile.rawFile);
//check exist thumbnail
if (folderInfo == undefined) {
if (folderThumbnailSelected.ThumbnailUrl != null) {
formData.append("ExistThumbnail", folderThumbnailSelected.ThumbnailUrl);
}
}
}
$.ajax({
url: folderUploadFolderThumbnailUrl,
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: formData,
success: function (e) {
var thumbnailFileName = e;
if (folderInfo != undefined) {
SaveFolderInfo(folderInfo, thumbnailFileName);
}
else {
InvokeSaveChanges(thumbnailFileName);
}
}
});
If this code run for the first time, it reach the ajax, pass to controller & return the filename to me, like this
var thumbnailFileName = e; //e= "onepiece.jpg"
After that, i can save the file normally. But many time after this i select the element again, this problem show up, when i debug the code at this
var formData = new FormData();
I find out it jump straight right into ajax, but never reach the controller, which return null & the thumbnail was never been save
var thumbnailFileName = e;// e=""
Can anybody know what cause this problem?
See also questions close to this topic
-
Why is my JavaScript object property inaccessible, when it IS, in fact, defined?
Here is the object. It is a second-level object in the data tree:
user: { userId: 3, username: 'aragorn', },
My React component is destructuring its parent object and making it available to the entire component. When I render the full user object using this code:
<p className="small"> {`Submitted by ${JSON.stringify(user)}`} </p>
I get a complete stringified object with all of user's properties:
When I try to access only the 'username' property from the 'user' object:
<p className="small"> {`Submitted by ${JSON.stringify(user.username)}`} </p>
I get this error:
Have you ever faced this weird issue before?
For further study, here is the full data object. This is coming from a mock data object being exported from a neighboring file in the same app. No network requests to a backend or anything, so there shouldn't be any async stuff going on here (I may be wrong):
{ title: "The Hefalump's Tale", page: '32', line: '1', author: 'Joni E. Driskill', genre: 'Sci-fi', type: 'Motivational', content: 'The grass is greener on the other side, unless, in actuality and reality, it is not. I guess in that case, you can just give up on anything nice in life.', claps: 23, id: 4, user: { userId: 3, username: 'aragorn', }, comments: [ { commentId: 0, quoteId: 0, content: 'Comment content', userId: 'userId', claps: 2, date: 2, }, { commentId: 1, quoteId: 1, content: 'Comment content', userId: 'userId', claps: 4, date: 1, }, { commentId: 2, quoteId: 2, content: 'Comment content', userId: 'userId', claps: 12, date: 0, }, ],
},
And HERE is my React component, called 'Meta,' bringing in the 'quote' object as a prop. The primary line in question is toward the bottom, but feel free to look at my props destructuring, too, if you like:
import React from 'react'; import Clap from '../mechanics/Clap'; import Report from '../mechanics/Report'; const Meta = ({ quote: { content, title, author, page, line, genre, type, claps, id, user, }, }) => ( <div className="discussion-meta mb2"> <h1>“{content}”</h1> <hr /> <div className="columns is-spaced-around pb3 text-align-left"> <div className="column"> <h3>{title}</h3> <p> <small>by {author}</small> </p> {page ? <p> <small>page {page}{line ? `, line ${line}` : ''}</small> </p> : null } </div> <div className="column text-align-right"> <p> <span className="tag-purple small">{genre}</span> </p> <p> <span className="tag-green small">{type}</span> </p> </div> </div> <div className="columns"> <div className="column"> <p className="small"> {`Submitted by ${JSON.stringify(user.username)}`} </p> </div> </div> <div className="columns"> <div className="column"> <Clap claps={claps} /> </div> <div className="column"> <Report id={id} /> </div> </div> </div> ); export default Meta;
I've recreated in CodeSandbox, and it works! WTF! https://codesandbox.io/s/4q9nlywl1x
-
Mongoose Save Nested Array of Objects - Node.js
I've created my model and can save an array of objects by manually listing them out, however this won't work in production because my array will not always be the same size.
Below is an example of my code. The issue I'm having when saving an array of objects under the stackRank field.
If anyone has any suggestions that would be great and a life saver!
Mongoose Model
const MySchema = mongoose.Schema({ userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User', require: true}, startDate: {type: Date, require: true}, endDate: {type: Date, require: false}, length: {type: Number, require: true}, inProgress: {type: Boolean, require: true, default: true}, stackRank:[{ appUsers: {type: mongoose.Schema.Types.ObjectId, ref: 'Users', require: true} }] });
Saving Code in Express
const mySchema = new MySchema({ userId: req.body.userId, startDate: today, length: req.body.startLength, stackRank: [ //TODO this is the part I need to change {appUsers: Array[0]}, {appUsers: Array[1]}, {appUsers: Array[2]} ] }); instantComp.save() .then((result) => { console.log('result from save', result) }) .catch(err => console.log('error promise all', err))
Desired Functionality
Instead of saving each value of the array individually for the field appUsers nested in stackRank, I want to be able to save the entire array at once because it will not always have a length of three. It will almost always vary in length so while the code I've written works for an array of this size, it won't actually function properly for me.
-
Android WebView: how to scroll to an <a name=here> position
I'm loading a self-created HTML page into a
WebView
in an Android app.The HTML page contains a tag like
<a name="here"></a>
somewhere in the middle.After loading that page, I'd like to be able to programmatically scroll to that position, as if I had clicked on a
<a href="#here">here</a>
link.I tried with
loadURL
and withloadDataWithBaseURL
, with every possible parameter combinations that I could think of, without success.Note 1: I want to be able to scroll to that position after the page has been already displayed.
Note 2: I cannot use
scrollTo(x,y)
because I don't know the y position of that<a name="here">
anchor within the page. If I could figure out the y position in the page of that<a name>
tag, that would also solve the problem, but I don't know how to find that y value either.(P.S. I'm loading the self-created HTML page by calling
loadDataWithBaseURL(null, _html, null, null, null);
where _html is the string with my HTML page) -
Only toggle certain elements based on class
I have a simple table:
<table> <tr class="header"> <th> .... </th> </tr> <tr class="level2"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level2"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> <tr class="level3"> <th> .... </th> </tr> </table>
This works great to toggle everything from one "header" to the next.
$('.header').click(function () { $(this).nextUntil('tr.header').toggle(); });
But what I can't figure out how to do is to ONLY toggle the elements with class of "level2" and leave "level3" hidden.
I've been playing around for a while with .toggleClass() and .netAll() but I am not getting it.
-
Unable to change the div color dynamically using VueJS
I am developing an application using Bootstrap and VueJS.
I am developing a Google drive like folder structure, wherein I want to highlight a div in blue when it is selected.
Here is the code:
export default{ mounted(){ $(document).ready(function () { let that = this; $("#div").on("click", ".folderRectangle", function () { $(that).css("background-color", "blue"); $(".folderRectangle").not(that).css("background-color", "white"); }); }); } }
.folderRectangle { x: 220px; y: 473px; width: 299px; height: 62px; background-color: #FFFFFF; border: 1px solid #BDBDBD; border-radius: 0px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div class="row"> <div class="col-xl-3 col-md-6"> <stats-card> <div slot="header" class="folderRectangle" id="div"> <div class="row"> <div class="col-3"> <div class="clearfix"> <i class="material-icons" id="folder-image"></i> </div> </div> <div class="col-9"> <div class="clearfix" style="position: relative"> <div> <p style="text-align: left">Folder Name</p> </div> <div> <p style="text-align:left">20 files</p> </div> </div> </div> </div> </div> </stats-card> </div> <div class="col-xl-3 col-md-6"> <stats-card> <div slot="header" class="folderRectangle" id="div"> <div class="row"> <div class="col-3"> <div class="clearfix"> <i class="material-icons" id="folder-image"></i> </div> </div> <div class="col-9"> <div class="clearfix" style="position: relative"> <div> <p style="text-align: left">Folder Name</p> </div> <div> <p style="text-align:left">20 files</p> </div> </div> </div> </div> </div> </stats-card> </div> </div>
When I try clicking on the div, I am unable to change the css color of the div using onClick. What wrong am I doing? Can someone please help me out?
-
How do I submit form without page reload taking into consideration the php script?
So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){ event.preventDefault(); var name = $("input#yourname").val(); var email = $("input#youremail").val(); if (name == ""){ $("input#yourname").focus; return false; } else{ } if (email == ""){ $("input#youremail").focus; return false; } });
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php function qis_verify_application(&$values, &$errors) { $application = qis_get_stored_application(); $register = qis_get_stored_application_messages(); $arr = array_map('array_shift', $application); foreach ($arr as $key => $value) { if ($application[$key]['type'] == 'multi') { $d = explode(",",$application[$key]['options']); foreach ($d as $item) { $values[$key] .= $values[$key.$item]; } } if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...')) $errors[$key] = 'error'; } $filenames = array('identityproof','addressproof'); foreach($filenames as $item) { $tmp_name = $_FILES[$item]['tmp_name']; $name = $_FILES[$item]['name']; $size = $_FILES[$item]['size']; if (file_exists($tmp_name)) { if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size']; $ext = strtolower(substr(strrchr($name,'.'),1)); if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type']; } } return (count($errors) == 0); } //qis_process_application in register.php function qis_process_application($values) { global $post; $content=''; $register = qis_get_stored_register ('default'); $applicationmessages = qis_get_stored_application_messages(); $settings = qis_get_stored_settings(); $auto = qis_get_stored_autoresponder(); $application = qis_get_stored_application(); $message = get_option('qis_messages'); $arr = array_map('array_shift', $application); if ($message) { $count = count($message); for($i = 0; $i <= $count; $i++) { if ($message[$i]['reference'] == $values['reference']) { $values['complete'] = 'Completed'; $message[$i] = $values; update_option('qis_messages',$message); } } } $filenames = array('identityproof','addressproof'); $attachments = array(); if ( ! function_exists( 'wp_handle_upload' ) ) { require_once( ABSPATH . 'wp-admin/includes/file.php' ); } add_filter( 'upload_dir', 'qis_upload_dir' ); $dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/'); foreach($filenames as $item) { $filename = $_FILES[$item]['tmp_name']; if (file_exists($filename)) { $name = $values['reference'].'-'.$_FILES[$item]['name']; $name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name)); $name = str_replace(' ','-',$name); $_FILES[$item]['name'] = $name; $uploadedfile = $_FILES[$item]; $upload_overrides = array( 'test_form' => false ); $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); array_push($attachments , WP_CONTENT_DIR .$dir.$name); } } remove_filter( 'upload_dir', 'qis_upload_dir' ); $content = qis_build_complete_message($values,$application,$arr,$register); qis_send_full_notification ($register,$values,$content,true,$attachments); qis_send_full_confirmation ($auto,$values,$content,$register); }
function qis_loop in quick-interest-slider.php
function qis_loop($atts) { $qppkey = get_option('qpp_key'); if (!$qppkey['authorised']) { $atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false; if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound'; } global $post; // Apply Now Button if (!empty($_POST['qisapply'])) { $settings = qis_get_stored_settings(); $formvalues = $_POST; $url = $settings['applynowaction']; if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period']; echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />"; die(); // Application Form } elseif (!empty($_POST['qissubmit'])) { $formvalues = $_POST; $formerrors = array(); if (!qis_verify_form($formvalues, $formerrors)) { return qis_display($atts,$formvalues, $formerrors,null); } else { qis_process_form($formvalues); $apply = qis_get_stored_application_messages(); if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked'); else return qis_display($atts,$formvalues, array(),'checked'); } // Part 2 Application } elseif (!empty($_POST['part2submit'])) { $formvalues = $_POST; $formerrors = array(); if (!qis_verify_application($formvalues, $formerrors)) { return qis_display_application($formvalues, $formerrors,null); } else { qis_process_application($formvalues); return qis_display_result($formvalues); } // Default Display } else { $formname = $atts['formname'] == 'alternate' ? 'alternate' : ''; $settings = qis_get_stored_settings(); $values = qis_get_stored_register($formname); $values['formname'] = $formname; $arr = explode(",",$settings['interestdropdownvalues']); $values['interestdropdown'] = $arr[0]; $digit1 = mt_rand(1,10); $digit2 = mt_rand(1,10); if( $digit2 >= $digit1 ) { $values['thesum'] = "$digit1 + $digit2"; $values['answer'] = $digit1 + $digit2; } else { $values['thesum'] = "$digit1 - $digit2"; $values['answer'] = $digit1 - $digit2; } return qis_display($atts,$values ,array(),null); } }
Do I have to edit any of the php and I also don't know what I have to write considering the php.
-
How to create dynamic variables from an ajax call to be used in a second, separate, ajax call
I'm setting up an "advanced search" form that is dynamically created using two api's that are specific to each user.
My first ajax call creates a multi input search form on page load. That call gives each input a specific id based on the search term.
{DisplayName: "Contract #", DataValue: "", DataType: "TEXT", DataField: "IDXT001"}
The second api holds the database the search inputs will be using. And the id's created in the first call match the search term id's of the second call.
{DisplayName: "Contract #", DataValue: "2222", DataType: "TEXT", DataField: "IDXT001"}
So, I need to be able to have the second ajax call use the id's assigned to the search term inputs from the first ajax call.
Based on what I have coded so far, I think I just need to make the search term id's as the filters for the second queryUrl. For that to work, the id's need to be held as variables that I can access for the second ajax call.
Is this the correct method? If so, how can I access the id's created and used as for the second call.
*I can include the url I am using, but it wouldn't work for others because it is locally hosted. Hopefully this can be solved with my explanation and the code I am showing.
First call:
$(document).ready(function() { $.ajax({ url: "http://domain/api/fieldsettings", method: "get", async: true, DataType: "application/json" }).then(data => { document.getElementById("test2").innerHTML = data .map(function(f) { console.log(f); return ( "<div class='span3'>" + "<label>" + f.DisplayName + ": " + " </label>" + "</input>" + "<input type='text' class='contract-input' id='" + f.DataField + "'>" + "</div>" ); }) .join("<br/>"); });
Second call:
$("#btn").on("click", function(event) { event.preventDefault(); var filter = $("#" + f.DataField).val(); var queryURL = "http://domain/api/masterdocument? filter=idxt001|" + filter; $.ajax({ url: queryURL, method: "GET", async: true, DataType: "application/json" }).then(data => { document.getElementById("test").innerHTML = data.map(function(f) { return f.Fields.map(function(e) { console.log(e); return "<p>" + e.DisplayName + ": " + e.DataValue + "</p>"; }).join("<br/>"); }); }); }); });
I get an error that f is not defined. Which is because f is not within the scope of my function.
-
Woocommerce display cart count via Menu as HTML
I am trying to display the cart count (refreshed using AJAX) via the default Woocommerce Menu navigation label as HTML.
I am obtaining the cart count through answers:
Following these answers, I believe I am obtaining the cart count correctly as follows:
add_filter( 'woocommerce_add_to_cart_fragments', 'wc_refresh_header_cart_count'); function wc_refresh_header_cart_count($fragments){ ob_start(); ?> <div id="header-cart-count"> <?php echo WC()->cart->get_cart_contents_count(); ?> </div> <?php $fragments['#header-cart-count'] = ob_get_clean(); return $fragments; }
Where I am struggling is to display the cart count as HTML, next to the Menu navigation label:
In Woocommerce -> Appearance -> Menus I am adding the HTML
<div id="header-cart-count"></div>
to try and display the cart item count, but it is not working. Am I using this correctly?I know that HTML can directly be called here for example as
<i class="fas fa-shopping-cart"></i>
works to display a cart icon. -
Cypress throwing cypress.io chrome-error://chromewebdata/ error when clicking a button
When clicking a button that takes me to another page, Cypress stops and just shows me a cypress.io chrome-error://chromewebdata/ error.
The code I'm using is simple:
cy.get('button').contains('Go Search').trigger('click')
And the code I'm attempting to click is this:
<button name="GoSearch" value="Go Search" onclick="navToPage('user/gosearch.cfm','');return false;">Go Search</button>
I think it may have something to do with this being an AJAX call, but not for certain. If it is, am I approaching this the wrong way?
-
How to protect a controller to only be visible from local network
I'm working on an ASP.NET MVC 5 site that will have some kind of subsite that requires to only be visible/reachable from computers that are inside the local network.
Basically every other controller different than this specific one will be visible for everybody (internet) but the one I want to protect should only be visible by individuals accessing the site from company's network.
I know I can create a site in IIS and create an application folder inside it to protect it using IIS configuration, but AFAIK that will require to build another ASP.NET MVC project that will be served by that application folder, so It will require to maintain two sites.
Is this possible to be configured by code/web.config or the only way is to create two MVC sites?
I will appreciate your help
-
How to send data using Input Model?
I have an interface to fill the fields, where you can add fields and delete them:
<form role="form" class="form-horizontal"> <div class="form-group bg-light text-center pt-3 pb-3"> <b><h3>Create Form</h3></b> </div> <div class="form-group"> <input type="text" class="form-control" placeholder="HeadField"> </div> <div class="form-group"> <textarea class="form-control" rows="5" placeholder="Description Field"></textarea><br> </div> <h5>Fields:</h5><br> <div class="border border-secondary rounded p-3" id="container"> <div class="field"> <div class="form-row"> <div class="form-group col-md-5"> <input class="form-control form-control-inline" placeholder="Head of field"> </div> <select class="selectBox form-control col-md-6 ml-4" onchange="addElement(this);"> <option value='textarea'>Typefield1</option> <option value='textarea'>Typefield2</option> <option value='textarea'>Typefield3</option> <option value='input'>Typefield4</option> <option value='input'>Typefield5</option> </select> <div class="form-group"> <input type="button" class="btn btn-default btn-xs col-md-1 ml-3" value="X" onclick="removeField(this);"><br> </div> </div> <div class='content'> </div> <div class="form-group"> <div class="form-check text-right"> <input class="form-check-input" type="checkbox" required/>Require<br> </div> </div> </div> </div> <div class="form-group text-right mt-3"> <input type="button" class="btn btn-success" value="addField" onclick="addField(this);"><br><br> </div> <div class="form-group mb-3"> <input type="submit" class="btn btn-success" value="Save"> <input type="button" class="btn btn-danger" value="Close"> </div> </form>
I need to use the input model to send data to the controller:
[HttpPost] public ActionResult EditForm(Model model) { //fill model in BD using Linq or ather...do something }
What should the input model look like in my case? Not sure, like this is called model binding, but I'm new to asp net mvc. addField:
function addField(btn) { var form = btn.closest("form"); if (form) { var div = form.querySelector(".field"); if (div) { var divCreated = document.createElement("div"); divCreated.className = div.className; divCreated.innerHTML = div.innerHTML; document.getElementById('container').appendChild(divCreated); } } }
And function addElement() adds element in div with id="content".
-
What does lifetime scope mean in Application_Start
When I configure a
DbContext
with Autofac as "lifetime scope", then in the scope of a request that means that it is disposed of at the end of a request.But what happens when we get a
DbContext
from the container in theApplication_Start()
method of an MVC application?We have a settings class that is set up as a singleton:
builder.RegisterType<Settings>().As<ISettings>().SingleInstance();
And in
Application_Start()
we get the settings from the container:var settings = DependencyResolver.Current.GetService<ISettings>();
The Settings class is dependent on a
DbContext
- and theDbContext
is set up in lifetime scopeWe know that this is a captive dependency, but do not think that is an issue, because the class uses the context once only.
My concern is whether the
DbContext
ever releases its resources.In
Application_Start()
are we in the scope of a request or are we in the scope of the application?And if we are in the scope of the application does "lifetime scope" mean that we don't dispose of the
DbContext
until the application stops?