Change Ajax from onclick to onsubmit - ajax

I would like to change the following code, at the moment the code reads data from the input box of an ajax table (seven script - ajax table editor) then when you click save it adds it to the table. I would like it so it does this when the user presses enter, how can I do this by modifying the code:
if(editTblRow==null && editTblCell==null){
if(fieldtype!='blob'){
$($('#ajaxtb')[0].rows[rowid].cells[cellid]).html('<input type="text" id="edit_box" class=\"edit_input\" value=\"' + id + '\" /><div class=\"cell_opts\">Save - Cancel</div>');
} else {
$($('#ajaxtb')[0].rows[rowid].cells[cellid]).html('<textarea id="edit_box" class=\"edit_input\" value=\"' + id + '\" >' + id + '</textarea> <div class=\"cell_opts\">Save - Cancel</div>');
}

Try using this JQuery function. It will help identify if the enter key is clicked.
$(document).keypress(function(e) {
if(e.which == 13) {
// Your code here
}
});

Related

Can't get wordpress ajax form to submit

I am porting an application to WordPress. It uses a form to select what attributes the customer is looking for in an Adult Family Home via checkboxes and drop-downs. It re-searches the database on each onchange and keyup. Originally I had the application standalone in PHP, but when I migrated it to WordPress I started having issues.
Currently in WP I have the code conditionalized ($DavesWay == 1) to do ajax the normal no-WordPress-way and ($DavesWay == 0) to do it the WordPress-way.
In the non-WordPress-way, the ajax works fine EXCEPT that I get a WP header and menu between the search form and the results-div that Ajax puts the data in. I get no errors from WP or in the JS console. In the WP-way The search form displayed, but nothing happens when I check any of the checkboxes. The JS console displays
POST http://localhost/demo4/wp-admin/admin-ajax.php 400 (Bad Request)
But I don't see any way to tell exactly what it is complaining about. How should I troubleshoot this?
Troubleshooting = Examine the HTML output, lots of echos and exits in PHP code, look at JS console.
function submitPg1(theForm) {
// Used with onChange from "most" form elements, but not on those that change the page
// rather than the select criteria. Such as rowsPerPage, pageNumber etc.
setById("pageNo", "1"); // set inital page
mySubmit();
}
function mySubmit(theForm) { // The actual ajax submit
// DO NOT set page number
jQuery.ajax({ // create an AJAX call...
data: jQuery("#asi_search_form").serialize(), // get the form data
type: jQuery("#asi_search_form").attr("method"), // GET or POST
url: jQuery("#asi_search_form").attr("action"), // the file to call
success: function (response) { // on success..
jQuery("#result").html(response); // update the DIV
}
})
}
function setById(id, value) { // Used to set vales by Id
x = document.getElementById(id).value;
x.value = value;
}
// 1st submit with blank selection
jQuery(document).ready(function () { submitPg1(this.form) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Code fragments: (from the displayed page source)
<div id="asi_container" class="asi_container" >
<noscript><h2>This site requires Javascript and cookies to function. See the Help page for how to enable them.</h2></noscript>
<div id="searchForm">
<form id="asi_search_form" name="asi_search_form" method="post" action="http://localhost/demo4/wp-admin/admin-ajax.php">
<input type="hidden" name="action" value="asi_LTCfetchAll_ajax" style="display: none; visibility: hidden; opacity: 0;">
<table id="greenTable" class="asi_table" title="The Green areas are for site administration, not typical users">
<tbody>
PHP code:
$DavesWay = 0;
if ($DavesWay == 1){ //echo "Daves Way Setup"; // Dave's way, which works but prints the menu twice
if( $operation == "submit"){
require("asi_LTCfetchAll.php"); // for each onchange or onkeyup
}else{
add_filter( 'the_content', 'asi_tc_admin', '12' ); // Initial page refresh # must be >12
}
}else{
// The WordPress way that I could't get to work -- asi_LTCfetch never gets called
function asi_LTCfetchAll_ajax(){
//echo "<br /> Goto to Submit function"; // DEBUG
require($asi_plugin_dir . "/includes" . '/asi_LTCfetchAll.php');
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // non-logged in users
add_filter( "the_content", "asi_tc_admin", "12" ); // Initial page refresh # must be >12
}
Try changing the JavaScript to the way WordPress recommends it in their documentation:
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
I suggest trying following URL: https://codex.wordpress.org/AJAX_in_Plugins
Also you can use the plugin: https://wordpress.org/plugins/ajax-search-lite/

Can I add a table into the message body with Outlook Add-in

I am working with Outlook Add-in. I have a task pane in message compose form which includes some textareas. Is it possible to add these information to the message body as a table?
The following is the part of my task pane ...
You are able to set and get body content of the message while in compose. Generate HTML table filled with user input you would like to appear in the message body. Retrieve current message body content with getAsync function. Add/insert the table you have generated into message body and set it back by using setAsync function. You may also use prependAsync function to manipulate with message body. Please read more information at Get and set item data in a compose form in Outlook.
The following code is just showing how to work(For 3 inputs). As you see in the question I have a button. Now I am able to add input's value which is in the taskpane to the message body as table by clicking button.
$("#btn1").click(function () {
Office.context.mailbox.item.body.getAsync(
"html",
{ asyncContext: "This is passed to the callback" },
function callback(result) {
Office.context.mailbox.item.body.setSelectedDataAsync(
'<table style = "background-color: red">' +
'<tr>' +
'<th>Shipment</th>' +
'<th>Payment</th>' +
'<th>Validity</th>' +
'</tr>' +
'<tr>' +
'<td>' + $("#shipmentText").val() + '</td>' +
'<td>' + $("#paymentText").val() + '</td>' +
'<td>' + $("#validityText").val() + '</td>' +
'</tr>' +
'</table>',
{ coercionType: Office.CoercionType.Html }
)
})
});

Ajax and output pdf file are not working together

I have a file named download.php and call getpdf function inside it.
I call download.php via ajax to download pdf file when users click download button. but nothing happend and no download window appears. I checked it in firebug Net tab and download.php are requested on click event. Its size also changes that shows the file is reading from its location,but no download window.
Here's getpdf code:
function getpdf($id) {
header('Content-Type: application/pdf');
readfile('/san/theo-books/PDFs/'.$id.'.pdf');
exit;
}
And here's download.php code:
$pdf_id = $_POST('pdi');
echo getpdf($pdf_id);
What is the problem? Would you help me?
Here is the full postback version. It's not using the jQuery Ajax, because Popup download window needs the full postback:
<a id="pdf-10" href="#">PDF Export</a>
$(document).ready(function () {
$('a[id^="pdf"]').click(function (event) {
event.preventDefault();
var pdfExportPath = "/san/theo-books/PDFs/";
var $a = $(this);
var postId = $a.attr('id').replace("pdf-","");
var form = $('<form action="' + pdfExportPath + '" name="pdf' + postId + '" id="pdf' + postId + '" method="POST"> <input id="id" name="id" type="hidden" value="' + postId + '" /></form>');
$(form).appendTo('body');
form.submit();
});
});

Values of a form's fields to an Ajax call using Dojo

I have a form like this (from a widget template):
'<div>' +
' <form data-dojo-type="dijit.form.Form" data-dojo-attach-point="form" method="POST"> ' +
' <label for="${id}_workspace">Workspace name</label> ' +
' <input name="workspace" id="${id}_workspace" data-dojo-attach-point="workspace" data-dojo-type="app.ValidationWorkspace" />' +
' <label for="${id}_password1">Password</label> ' +
' <input name="password[0]" id="${id}_password1" data-dojo-attach-point="password1" data-dojo-type="app.ValidationPassword" />' +
' <label for="${id}_password1">Confirm password</label> ' +
' <input name="password[1]" id="${id}_password2" data-dojo-attach-point="password2" data-dojo-type="app.ValidationPassword" />' +
' <input type="submit" data-dojo-attach-point="button" data-dojo-type="app.BusyButton" label="Create!" />' +
' </form>' +
'</div>',
In the code, I wrote:
data = {};
data.workspace = that.workspace.get('value');
data.password = [];
data.password[0] = that.password1.get('value');
data.password[1] = that.password2.get('value');
// Store the data
g.stores.workspacesAnon.put(data).then(
function(res){
console.log("Jsonrest put(data) returned OK: " + json.toJson(res) );
that.button.cancel();
}
);
Two actual questions:
If I use that.form.value.email instead of that.password1.get('value'), sometimes outdated values are submitted to the form (!). For example, if I type something in the password2 field and hit enter straight away, the actual submission happens for the expected in Dojo? How come does it happen?
Is there a better way to get the form's values, so that 'password[0]' and 'password[1]' become an array automatically etc.?
Every widget under dijit.form makes sure that the one form element with the correct name is updated with its value, even if the values are something like a filtering select click or a date in a calendar.
With that said, we know that a common form.submit() will work as expected.
However while doing the submission as an AJAX request, we need to loop the form-elements for their values and make it a json key value object.
You have it easy, dojo.xhrPost does this internally if called like this:
dojo.xhrPost ( {
url: 'submiturl.sapi',
form: dojo.byId('myFormDomId')
} )
For higher level of control you can use either dojo.formToJson or dijit.form.Form.getValues - e.g. these two variants
var values = dojo.formToJson(dojo.byId('myFormDomId'));
// OR
var values = dijit.byId('myFormDijitId').getValues();
// mod or mixin your custom values, examplewise
values = dojo.mixin(values, { anotherVariable: 'sentAsPostParam' });
dojo.xhrPost ( {
url: 'submitUrl.sapi',
content : values
} );
In regards to your first question 1)
If a validator is attached to the widget email - and the validation renders in-valid, the input element is not set accordingly. Setting value is done once there's either 1 - keyup event or 2 - onblur event. To ensure that correct values are sent, use dijit.form.Form.validate (seeing as you allready have extended your form dojoType) like this
var formWidget = dijit.byId('myFormDijitId');
if(formWidget.validate()) { // loops all form widgets and 'sums' up their validators
dojo.xhrPost( { url: 'submiturl.sapi', content: formWidget.getValues() } );
}
EDIT:
specifically for creating a nested array within the item, OP needs for the JsonRest store - it is nescessary to call the input elements by the excact same name, e.g.
<input name="password"
id="${id}_password1" data-dojo-attach-point="password1" data-dojo-type="app.ValidationPassword" />
<input name="password"
id="${id}_password2" data-dojo-attach-point="password2" data-dojo-type="app.ValidationPassword" />
Also, make use of dojo.formToJson on the native form element, like so (do it after validation to assert values being set):
g.stores.workspacesAnon.put(
dojo.formToJson(widgetReference.form.domNode)
).then( ... );
you could use dojo.xhrPost() specifying your form, see this link and take a look at example 1 where it sends the dojo.byId("myform") . I'm guessing you can call it this way and not worry about how to pass those parameters to the server. That should fix the issue of sending outdated parameters.
If you need anything comment on this.
Luck,

jQuery cleditor plugin: creating a new button

Using cleditor, I'm trying to set up a custom button with the following code:
(function($) {
$.cleditor.buttons.link_species = {
name: "link_species",
image: "fish.gif",
title: "Species Link",
command: "inserthtml",
popupName: "link_species",
popupClass: "cleditorPrompt",
popupContent: "Genus: <input type='text' size='15'> Species: <input type='text' size='15'><br />Remove italics? <input type='checkbox' value='remove'> <input type='button' value='Ok' />",
buttonClick: link_speciesClick
};
// Handle the hello button click event
function link_speciesClick(e, data) {
// Wire up the submit button click event
$(data.popup).children(":button")
.unbind("click")
.bind("click", function(e) {
// Get the editor
var editor = data.editor;
var $text = $(data.popup).find(":text"),
genus = $text[0].value,
species = $text[1].value;
var slug = genus + '-' + species;
slug = htmlEntities(slug);
var link = '/dev/species/' + slug + '/';
var rel = link + '?preview=true';
var display = firstUpper(genus) + ' ' + species;
// Get the entered name
var html = '' + display + '';
if ( !$(data.popup).find(":checkbox").is(':checked') ) {
html = '<em>' + html + '</em>';
}
// Insert some html into the document
editor.execCommand(data.command, html, null, data.button);
// Hide the popup and set focus back to the editor
editor.hidePopups();
editor.focus();
});
}
})(jQuery);
It's a WordPress website, and the directory structure is something like this:
/wp-content/plugins/sf-species-profile/cleditor
Within there I have all the cleditor files and config.js.This file is where the above code is stored.
I also have an images folder containing a 24*24 fish.gif file.
For some reason, when I run this code, I get the following error:
[firefox]
a is undefined
<<myurl>>/wp-content/plugins/sf-species-profiles/cleditor/jquery.cleditor.min.js?ver=3.3.1
Line 17
[chrome]
Uncaught TypeError: Cannot read property 'length' of undefined
If I change the "image" argument to image:"" the same image for "B" appears, but the plugin works without error.
Does anyone have any ideas what may be wrong?
It would be easier to debug with the non minimized version. You can get it from here: http://premiumsoftware.net/cleditor/ (zip)
There are 2 functions that include a length call in the code that ends up in line 17 of the minimized code. One in the function hex(s) that processes color. The other is the the imagePath function.
function imagesPath() {
var cssFile = "jquery.cleditor.css",
href = $("link[href$='" + cssFile +"']").attr("href");
return href.substr(0, href.length - cssFile.length) + "images/";
}
It could throw an error of the type you have if your rendered html doesn't include a line like "<link rel="stylesheet" type="text/css" href="path/to/jquery.cleditor.css" />". (Href would then be undefined.)
For wordpress integration, you may find it easier to setup when using the wordpress plugin version of cleditor.

Resources