I'm having a hard time with impromptu(jquery plugin) where I keep getting an undefined value. Here is an example:
<img id=dispatch title='Click to dispatch(COMING SOON)' onclick=Dispatch(0) src='../images/icons/truck_green.png' width=16 height=16/>
<img id=dispatch title='Click to dispatch(COMING SOON)' onclick=Dispatch(1) src='../images/icons/truck_green.png' width=16 height=16/>
<img id=dispatch title='Click to dispatch(COMING SOON)' onclick=Dispatch(2) src='../images/icons/truck_green.png' width=16 height=16/>
<img id=dispatch title='Click to dispatch(COMING SOON)' onclick=Dispatch(3) src='../images/icons/truck_green.png' width=16 height=16/>
function Dispatch(id){
var driver = 'Enter the drivers name:<br><input type="text" id="alertName" name=myname value="" />';
$.prompt(driver,{
submit: myfunc,
buttons: { Ok:true }
});
}
function myfunc(e,v,m,f){
var an = m.children('#alertName');
if(f.alertName == ""){
an.css("border","solid #ff0000 1px");
return false;
}
return true;
}
Eventually I want to take the id and the name typed and do some AJAX. But I cant get the css change. I alerted f.alertName and got undefined and I don't know why. Thank for your help.
I believe you want f.myName. Learn to step through with debugger and examine objects. The answer quickly became obvious.
http://jsfiddle.net/ULeQz/1/
var driver = 'Enter the drivers name:<br><input type="text" id="alertName" name="myname" value="" />';
$.prompt(driver, {
submit: myfunc,
buttons: {
Ok: true
}
});
function myfunc(e, v, m, f) {
debugger;
var an = m.children('#alertName');
if (f.myname == "") {
an.css("border", "solid #ff0000 1px");
return false;
}
return true;
}
Related
Please find the below code snippet:
HTML:
<div>
<span> First Name : <input type="text" id="firstName" name="First Name"/></span>
</div>
<br/>
<div>
<span>Student Id: <input type="text" id="studentId" name="studentId"/></span>
<span>Teacher Id: <input type="text" id="teacherId" name="teacherId"/></span>
</div>
<br/>
<div>
<span>Student Name : <input type="text" id="stdLastName" name="stdLastName"/></span>
<span>Student Age :<input type="text" id="stdAge" name="stdAge"/></span>
</div>
<br/>
<div>
<span>Teacher Name : <input type="text" id="tchrLastName" name="tchrLastName"/></span>
<span>Teacher Age : <input type="text" id="tchrAge" name="tchrAge"/></span>
</div>
<br/>
<input type="button" value="Submit" id="submit"/>
Javascript:
$('#firstName').focus();
var d1= new $.Deferred();
$('#firstName').blur(populatePage());
//called on blur of first name
function populatePage() {
$.when(populateStdDetails(),populateTchrDetails()).done(function(resp1, resp2){
$('#stdLastName').val(resp1[0].stdName);
$('#stdAge').val(resp1[0].age);
$('#tchrLastName').val(resp2[0].stdName);
$('#tchrAge').val(resp2[0].age);
console.log('All details populated....');
d1.resolve();
});
return d1;
}
//first ajax call
function populateStdDetails() {
if($('#firstName').val() != '' && $('#studentId').val() !='') {
return $.ajax({
url : '/someURL?studentId='+studentId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
}
}
//second ajax call
function populateTchrDetails() {
if($('#firstName').val() != '' && $('#teacherId').val() !='') {
return $.ajax({
url : '/someURL?teacherId='+teacherId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
}
}
$('#submit').click(function(e){
//wait for the ajax calls to be completed
$.when(populatePage()).done(function(e){
console.log('All done !!!!');
//Move to next page;
});
});
The First Name text field has an onblur event attached which works fine in usual scenario but when the focus is on "First Name" and "Submit" is clicked, the submit function is called instead of waiting for the onblur event to be completed.
You have placed deferred.resolve in wrong places in your timeout functions. Do it like this way:
function doSomething(deffered) {
$('#log').append('doSomething');
deferred.resolve();
return deferred;
};
function ajaxRequests1(deferred) {
setTimeout(function(){
$('#log').append('......ajaxRequests1');
deferred.resolve();
}, 1000);
return deferred;
};
function ajaxRequests2(deferred) {
setTimeout(function(){
$('#log').append('.....ajaxRequests2');
deferred.resolve();
}, 5000);
return deferred;
};
var func1 = function () {
var promise = new $.Deferred();
ajaxRequests1(promise);
return promise;
}
var func2 = function () {
var promise = new $.Deferred();
ajaxRequests2(promise);
return promise;
}
var stepFinal = function() {
var promise = new $.Deferred();
doSomething(promise);
return promise;
}
$.when(func1().promise(), func2().promise())
.done(function () {
stepFinal().done();
});
OK, if you want populatePage() to be called when focus leaves #firstname, and if the user also clicked on the submit button and you want the submit operation to wait for that blur action to finish, you can do this:
$('#firstName').blur(function(e) {
// call populatePage and set the resulting promise as a data item so
// the submit handler can get access to it
var self = $(this);
var p = populatePage();
self.data("blurPromise", p);
// when this promise is done, clear the blurPromise
p.always(function() {
self.removeData("blurPromise");
});
});
//called on blur of first name
function populatePage() {
return $.when(populateStdDetails(),populateTchrDetails()).done(function(resp1, resp2){
$('#stdLastName').val(resp1[0].stdName);
$('#stdAge').val(resp1[0].age);
$('#tchrLastName').val(resp2[0].stdName);
$('#tchrAge').val(resp2[0].age);
console.log('All details populated....');
});
}
//first ajax call
function populateStdDetails() {
if($('#firstName').val() != '' && $('#studentId').val() !='') {
return $.ajax({
url : '/someURL?studentId='+studentId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
} else {
// just return already resolved promise
return $.when();
}
}
//second ajax call
function populateTchrDetails() {
if($('#firstName').val() != '' && $('#teacherId').val() !='') {
return $.ajax({
url : '/someURL?teacherId='+teacherId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
} else {
return $.when();
}
}
$('#submit').click(function(e){
// get blur promise or dummy resolved promise
var p = $("#firstName").data("blurPromise") || $.when();
p.then(function() {
// do your submit logic here
// The onBlur handler is done now
});
});
Things I've updated in your promise handling code:
Use the $.ajax() promises directly without wrapping them in yet another promise.
Use the $.when() promises directly without wrapping them in yet another promise.
When using an if statement to decide whether or not to execute an asynchronous operation, it is usually best to also return a promise in the else arm so your function consistently always returns a promise. If there's nothing else to do in the else clause, then a shortcut for returning an already resolved promise in jQuery is to just return $.when();.
Be warned that .done() is jQuery-specific and not standard promise behavior. If you're already on jQuery 3.x or higher, then you should probably switch to .then() and then your promises will behave like the promise standard.
Is it possible to combine Google's incredible reCAPTCHA and Matias Meno's incredible dropzone.js, to prevent attacks and deter spam bots?
Using wordpress.
This is what I came up with following a few tutorials:
SO answer
codeforgeek
And some others I dont remember
// Dropzone.autoDiscover = false; //I use Autodiscover
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
previewsContainer: '.fileupload',
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
// myDropzone.processQueue();
var valid = true;
$('[data-required]').each(function(i,ele){
if(ele.value == ''){
$(this).parent().parent().addClass('alert');
valid = false;
}
});
if (!valid){
e.preventDefault();
scrollTop();
return false;
}
// Get the recaptcha input
var cap_input = grecaptcha.getResponse();
$.ajax({
url: homeUrl+'/wp-admin/admin-ajax.php',
type: "POST",
dataType: "JSON",
data: {
"action": "verifyReCaptcha",
"g-recaptcha-response": cap_input
},
success: function(response){
console.log(response);
if(response == 'Good captcha'){
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
}
else {
// Upload anyway without files
if (wantToUpload == 'unknown') {
$('#noFiles').modal();
e.preventDefault();
return false;
}
else if (wantToUpload == false) {
myDropzone.uploadFiles([ ]);
}
else {
myDropzone.uploadFiles([ ]);
}
}
}
else{
console.log('Spammer go away');
$('.g-recaptcha').addClass('alert');
}
}
});
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
console.log('sending');
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
console.log('success');
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
console.log('error');
});
}
}
And some html/php
<form name="" action="<?=get_permalink();?>" method="post" id="my-awesome-dropzone" class="dropzone" enctype="multipart/form-data">
<label class="label" for="text-435">
<?=__('Name*','gt_domain');?>
</label>
<input type="text" name="client-name" value="" size="40" class="input__field--manami" id="text-435" data-required="true">
<!-- Lots of input fields -->
<div class="col-md-8 col-xs-12 fileupload dropzone-previews dz-message">
<h2 class="text-center" id="fileuploadtext">
<?=__('Click or drag and drop your file here <br>(Max 60mb)','gt_domain');?>
</h2>
</div>
<div class="g-recaptcha" data-sitekey="MY_PUBLIC_KEY"></div>
<input class="dangerzone-submit" type="submit" value="<?=__('Request quote','gt_domain');?>" name="dangerzone-submit">
</form>
And for ajax validation before submitting the form:
function verifyReCaptcha(){
$email;
$comment;
$captcha = false;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo json_encode('Please check the the captcha form.');
exit;
}
$response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MY_SUPER_SECRET_GOOGLE_RECAPTCHA_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false){
echo json_encode('You are spammer ! Get the #$%K out');
}
else{
echo json_encode('Good captcha');
}
exit;
}
add_action( 'wp_ajax_nopriv_verifyReCaptcha', 'verifyReCaptcha' );
add_action( 'wp_ajax_verifyReCaptcha', 'verifyReCaptcha' );
And finnaly recieve form inputs and images:
<?php
if (isset($_POST['dangerzone-submit'])) {
// print_r($_POST);
$client = $_POST['client-name'];
$email = $_POST['email'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if ($_FILES) {
foreach ($_FILES as $file => $array) {
// print_r($array);
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK && $_FILES[$file]['error'][0] !== 0) {
echo "upload error : \n";
print_r($_FILES[$file]['error']);
print_r($_FILES);
die();
}
$uploads_dir = ABSPATH . 'wp-content/uploads/dropzone/';
$external_link = get_home_url().'/wp-content/uploads/dropzone/';
foreach ($array['name'] as $key => $val) {
print_r($key);
$name = $array['name'][$key];
$tmp_name = $array['tmp_name'][$key];
$newfilename = wp_unique_filename( $uploads_dir, $name );
$movefile = move_uploaded_file($tmp_name, $uploads_dir.$newfilename);
$uploaded_files[] = $external_link.$newfilename;
}
}
}
sendMail( //My func for sending mail
$client,
$email,
$company,
$phone,
$comments,
$uploaded_files
);
}
?>
I am about to integrate svg-edit to an ASP.NET MVC project.
Is there anyone who has a recommendation or tutorial on how to begin with?
Thank you.
I am answering my own question.
After a research, I recommend deploying the whole SVG-EDIT lib into mvc architecture, then modify the embed api as following:
This is my Partial View and JS file that call the embed api and put it into the iframe within the partial view:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
// Make sure to add the embedapi into the html file, becuase the intialization function runs actually in that file, all this call does is basically to take the iframe from html and inialize the api within that tag.
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here I have a save and load functions ready for the module: There is so much work to do in order to perfect the algorithm, but since this was just a test project to figure out the possibility of integrating the module into the environment I put enough effort to understand that share the knowledge with the community:
Here is my cshtml file:
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here is the js file:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
document.write("<script src='~/Scripts/jquery-1.10.2.js'></script>");
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
$(document).ready(function () {
// jquery selectro
$("#save1").click(function () {
$("#DivData").append("<b>Appended text</b>");
});
});
$(document).ready(function(){
$("#CloseSVG").click(function () {
$("#svg").hide();
});
});
function HandleSvgData(data,error) {
if (error) {
alert('Error:' + error);
} else {
$('#DivData').append(data);
alert(data);
}
}
function handleSvgData(data, error) {
alert("handling Data");
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
}
}
function save1() {
alert("saving");
// svgCanvas.getSvgString()(handleSvgData);
$("#svgedit").append($('This is the test classed appended after DivDat'));
}
function AddNewElemnt()
{
var newElement = document.createElement("Test");
var newNode = document.createTextNode("This is my new node!");
newElement.appendChild(newNode);
var referenceElement = document.getElementById("mainBody");
var tagInsert = document.getElementById("TestId");
referenceElement.insertBefore(newElement, tagInsert);
// alert("added");
}
function Postt(data) {
}
function Post(data) {
var mainBody = document.getElementById("mainBody");
var SvgDataId = prompt("give me primary id");
var SvgUser = prompt("give me UserName");
var form = document.createElement("form");
form.setAttribute("id", "PostData");
form.setAttribute("action", "/SvgDatas/Create");
form.setAttribute("method", "post");
mainBody.appendChild(form);
var PostData = document.getElementById("PostData");
var InputSvgDataId = document.createElement("input");
InputSvgDataId.setAttribute("name", "SvgDataId");
InputSvgDataId.setAttribute("value", SvgDataId);
PostData.appendChild(InputSvgDataId);
var InputSvgUser = document.createElement("input");
InputSvgUser.setAttribute("name", "SvgUser");
InputSvgUser.setAttribute("value", SvgUser);
PostData.appendChild(InputSvgUser);
var InputData = document.createElement("input");
InputData.setAttribute("name", "Data");
InputData.setAttribute("value", data);
PostData.appendChild(InputData);
form.submit();
}
function save() {
var doc, mainButton,
frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
// Hide main button, as we will be controlling new, load, save, etc. from the host document
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
mainButton.style.display = 'none';
// get data
svgCanvas.getSvgString()(function handleSvgData(data, error) {
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
Post(data);
}
});
}
/*
function BuidUrl(SVGUser) {
var uri = prompt("Give me url where the serach function lives, if empty then I will use Razor syntax to call within MVC architescture");
if (uri)
return uri;
else {
var urlHelper = ('http://localhost:53546/SvgDatas/Search?id='+SVGUser);
return urlHelper;
}
}
*/
function returnedData_IntializeEditor(data, status) {
if ((data != null) && (status == "success")) {
var frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
tool_Bottum = doc.getElementById("#tool_button");
mainButton.style.display = 'none';
// Open Data into the frame
// var svgexample = '<svg width="640" height="480" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><g><title>Layer 1<\/title><rect stroke-width="5" stroke="#000000" fill="#FF0000" id="svg_1" height="35" width="51" y="35" x="32"/><ellipse ry="15" rx="24" stroke-width="5" stroke="#000000" fill="#0000ff" id="svg_2" cy="60" cx="66"/><\/g><\/svg>';
svgCanvas.setSvgString(data.Data);
} else {
$("#svg").append("<li>There is not such a data available in the database!</li>");
}
}
function LoadExample() {
var SVGUser = prompt("Enter the SVG ID");
$.getJSON("http://localhost:53546/SvgDatas/Search?id=" + SVGUser, returnedData_IntializeEditor );
}
This is the model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace IntegrationOfSVG.Models
{
public class SvgData
{
public string SvgDataId { get; set; }
public string SvgUser { get; set; }
public string Data { get; set; }
}
}
Thank you SVG-EDIT community for the great tool.
Next I am planning to add a view mode to this module that opens the data from a sequal server and if the mode is admin, lets the user to edit the existing data. I will keep this posted updated.
1- One way is to remove the tools from the client side, but it has a certain limitation that is the fact that css does not adjust a
function RemoveTools() {
var frame = document.getElementsByClassName("iFrameHtmlTag")[0];
doc = frame.contentWindow.document;
if (doc != null) {
var Tools = [
'tools_top', 'tools_left', 'tools_bottom', 'sidepanels', 'main_icon', 'rulers', 'sidepanels', 'canvashadow'];
for (i=0; i<Tools.length;i++)
{
doc.getElementById(Tools[i]).style.display = "none";
}
} else
alert("Doc was null");
};
$(document).ready(function () {
$("#hide").click(function () {
RemoveTools();
});
});
It is an effective way, but there should be a better method to view the object with few parameters also to readjust the size of the window. I will continue with that topic too.
I have issue about the live search with check box. My problem is when i search one the name list the check box is automatically check. only the showed data check.
example i search world "vin"
all have word vin must be checked.
this is my [sample][1]
[1]: http://jsfiddle.net/v921/TxYqv/3/
UPDATED answer:
Here is how your js should look like:
function filter(element) {
var $trs = $('.AvailableGroupLab tr').hide();
var regexp = new RegExp($(element).val(), 'i');
var $numberOfShownRows = 0;
var $rows = $trs.filter(function () {
if($(element).val() != "")
{
$(this).children(':nth-child(1)').html("<input type='checkbox' checked />");
}
else
{
$(this).children(':nth-child(1)').html("<input type='checkbox' />");
}
return regexp.test($(this).children(':nth-child(2)').text());
});
$rows.show();
if($rows.length == 0)
{
$('#message').show();
}
else
{
$('#message').hide();
}
}
$('input:text').on('keyup change', function () {
filter(this);
})
And put this div whereever you want to put your text:
<div id="message" style="display:none"> No record! </div>
I am trying to add an ajax function to a script that does 2 things essentially:
Step 1: Determine if it needs to search for users or create a new one
Step 2: Based on selection 1, it will either go to the selected script (that part works) or call a new function (that part doesn't work, yet). Now, I know the 2nd function itself works perfectly as I called it directly in the anchor tag and had no issues, so it has to be in how I am trying to all it witin the function itself. here's what I have so far:
function changecm(){
var txt = 'Select An Option To Continue:<br>
<input type="radio" name="type" id="type" value="search" style="font-size:22px;"><br>
<input type="radio" name="type" id="type" value="create" style="font-size:22px;">';
$.prompt(txt,{
buttons:{Confirm:true, Cancel:false},
submit: function(v,m,f){
var flag = true;
if (v) { }
return flag;
},
callback: function(v,m,f){
if(v){
var type = f.type;
if(type == 'create'){
$.post('changecm',{type:type},
function(data){
$("div#customer").html(data);
}
);
}
else{
function(changecmnow);
}
}
}
});
}
That's function 1. Here's function 2:
function changecmnow(){
var txt = 'Enter the first name, last name, or telephone number of the customer to limit your results:<br>
<input type="text" name="terms" id="terms" style="font-size:22px; width:400px;">';
$.prompt(txt,{
buttons:{Confirm:true, Cancel:false},
submit: function(v,m,f){
var flag = true;
if (v) { }
return flag;
},
callback: function(v,m,f){
if(v){
var terms = f.terms;
$.post('changecm',{terms:terms},
function(data){
$("div#customer").html(data);
}
);
}
}
});
}
if you just want to invoke the function, why not just
else { changecmnow();
}