I'm trying to use jquery to select some hidden fields to retrieve some values from a certain row in a a table to make an ajax call. The first variable (ebId) is retrieved fine, but all of the other ones don't ever get set. They're all null. I can't use the name of the hidden field because these hidden fields are dynamically created and would have the same same. So i'm trying to use a class. Any idea why the way that I'm selecting the last 3 variables (_product,_applicantType,_ssn) isn't working?
Here's the JQuery and the pertinent HTML
$('.submissionStatus').click(function () {
var _ebId = $(this).next('.ebId').val();
var _product = $(this).next('.product').val();
var _applicantType = $(this).next('.applicantType').val();
var _ssn = $(this).next('.ssn').val();
$.ajax({
type: 'GET',
data: { ebId: _ebId, product: _product, applicantType: _applicantType, ssn: _ssn },
url: '#Url.Action("GetSeverityErrors", "AppListing")',
success: function (data) {
alert('Call success')
$(this).next('.loaded').val(true);
},
error: function (xhr, status, error) {
alert('An Error Occured.');
}
});
});
<input type="hidden" class="ebId" value="#item.ElectedBenefitId" />
<input type="hidden" class="product" value="#item.Product" />
<input type="hidden" class="applicantType" value="#item.ApplicantType" />
<input type="hidden" class="ssn" value="#item.Ssn" />
A little more HTML insight:
<td align="left">
<a style="color:red;" class="submissionStatus" href="javascript: void(0)" title="SubmissionStatus">#item.SubmissionStatus.ToPrettyString()</a>
<input type="hidden" class="ebId" value="#item.ElectedBenefitId" />
<input type="hidden" class="product" value="#item.Product" />
<input type="hidden" class="applicantType" value="#item.ApplicantType" />
<input type="hidden" class="ssn" value="#item.Ssn" />
<input type="hidden" class="loaded" value="false" />
</td>
note that closest() selects closest parent element based on it's parameter, try this:
var _ebId = $(this).siblings('input.ebId').val();
var _product = $(this).siblings('input.product').val();
var _applicantType = $(this).siblings('input.applicantType').val();
var _ssn = $(this).siblings('input.ssn').val();
$('.submissionStatus').click(function () {
var storThis = this;
var _ebId = $(storThis).next('.ebId').val();
var _product = $(storThis).next('.product').val();
var _applicantType = $(storThis).closest('.applicantType').val();
var _ssn = $(storThis).closest('.ssn').val();
Related
I am trying to upload a PDF file to Google Drive and insert the link to the file in Google Sheets. Here is the ajax:
$.ajax({
type: 'POST',
url: 'https://script.google.com/macros/s/AKfycbxyjjBv84uONFouZaiNeC2xwoMPP3p-3dzYxbQBCbJnEza0aPn-/exec',
data: serializedData,
success: function(result) {
var myMessage = $(document.activeElement).attr('id');
$('#sucessMessage2').html('<div class=\"successActive\">Your application has been successfully sent</div>');
document.getElementById("regform").reset();
},
error : function(error) {
alert('Error: Something went wrong. Please refresh the page and try again');
}
});
Here is the HTML:
<form id="regform">
<input id="FirstName" tabindex="1" name="FirstName" type="text" placeholder="First Name *" />
<input id="LastName" tabindex="2" name="LastName" type="text" placeholder="Last Name *" />
<input id="Occupation" tabindex="3" name="Occupation" type="text" placeholder="Occupation" />
<input name="Resume" type="file" tabindex="4" /><br/>
<div class="successMessage" id="sucessMessage2"></div>
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" value="Submit Application to Rent" />
</form>
And Code.gs:
var SHEET_NAME = "Sheet1";
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Everything is populating in the Google Sheet, but I have no idea how to get the Resume to upload to Google Drive and add the link to the Google Sheet.
You can upload a file to drive with a combination of FileReader and google.script.run as following:
Modify <input name="Resume" type="file" tabindex="4" /><br/>
to
<input id = "pdf" name="Resume" type="file" tabindex="4" /><br/>
Modify
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" value="Submit Application to Rent" />
to
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" onClick="formSubmit()" value="Submit Application to Rent" />
Write the javascript function:
function formSubmit() {
var pdf = document.getElementById("pdf").files[0];
var reader = new FileReader();
if (pdf) {
reader.readAsDataURL(pdf);
reader.onloadend = function () {
google.script.run.getResume(reader.result);
}
}
}
In Code.gs, add the function
function getResume(pdf){
var mimeType = pdf.substring(5,pdf.indexOf(';'));
var bytes = Utilities.base64Decode(pdf.substr(pdf.indexOf('base64,')+7));
var title='my_pdf';
var blob = Utilities.newBlob(bytes, mimeType, title);
var file=DriveApp.createFile(blob);
var link = file.getUrl();
Logger.log(link);
}
Integrate link into your existing code as desired, e.g. push it into row and into the spreadsheet.
Explanation: You convert with FileReader the content of the pdf file
into a data URL. Apps Script can use this data URL to read the file as
a blob and convert the blob into a file on your drive.
UPDATE
A sample how to pass the form data completely with google.script.run without Ajax:
Index.html:
<form id="regform">
<input id="FirstName" tabindex="1" name="FirstName" type="text" placeholder="First Name *" />
<input id="LastName" tabindex="2" name="LastName" type="text" placeholder="Last Name *" />
<input id="Occupation" tabindex="3" name="Occupation" type="text" placeholder="Occupation" />
<input id = "pdf" name="Resume" type="file" tabindex="4" /><br/>
<input class="btn-submit" id="submitFormTwo" tabindex="5" type="submit" onClick="formSubmit()" value="Submit Application to Rent" />
</form>
<script>
function formSubmit() {
var firstName = document.getElementById("FirstName").value;
var lastName = document.getElementById("LastName").value;
var occupation = document.getElementById("Occupation").value;
var pdf = document.getElementById("pdf").files[0];
var reader = new FileReader();
if (pdf) {
reader.readAsDataURL(pdf);
reader.onloadend = function () {
google.script.run.withSuccessHandler(success).withFailureHandler(error).getResume(firstName, lastName, occupation, reader.result);
}
}
}
function success(){
alert ("Your application has been successfully sent");
}
function error(){
alert ("There was an error");
}
</script>
Code.gs
function doGet(){
return HtmlService.createHtmlOutput("index.html");
}
function getResume(firstName, lastName, occupation, pdf){
var mimeType = pdf.substring(5,pdf.indexOf(';'));
var bytes = Utilities.base64Decode(pdf.substr(pdf.indexOf('base64,')+7));
var title='my_pdf';
var blob = Utilities.newBlob(bytes, mimeType, title);
var file=DriveApp.createFile(blob);
var link = file.getUrl();
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
var values = [firstName, lastName, occupation, link];
var nextRow = sheet.getLastRow()+1;
sheet.getRange(nextRow, 1, 1, values.length).setValues([values]);
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
I have this form, and I would like to send these values. I know we have to use setState() to store data but how does it work for input type="hidden"?
First question: How to store input hidden to setState ?
Second question: How to serialize data like form.serialize() ?
Third question: How to send these serialize values? Ajax or Axios, who is the better?
Here is the code:
handleSubmit(e) {
e.preventDefault();
/**
$.ajax({
url: "post.php",
type: "POST",
data: DATA,
success:function(data) {
}
});
**/
}
<form onSubmit={this.handleSubmit}>
<input type="hidden" name="action" value="login" />
<input type="email" name="email_user" placeholder="Email" />
<input type="password" name="password_user" placeholder="Mot de passe" />
<button type="submit">Login</button>
</form>
The answer is complex for all your questions.
First of all, it depends on the task: if you just want to send asynchonous request to server on form submit, you don't need to use Component state. Here is a link to the relevant section of the documentation. And use refs to access inputs data.
class FormComponent extends React.Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
e.preventDefault();
// Send your ajax query via jQuery or Axios (I prefer Axios)
axios.get('your_url', {
params: {
action: this.actionInput.value,
email: this.emailInput.value,
password: this.passwordInput.value,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input type="hidden" name="action" value="login"
ref={(input) => { this.actionInput = input }} />
<input type="email" name="email_user" placeholder="Email"
ref={(input) => { this.emailInput = input }}/>
<input type="password" name="password_user" placeholder="Mot de passe"
ref={(input) => { this.passwordInput = input }}/>
<button type="submit">Login</button>
</form>
);
}
}
All data can be stored on React's state, but if you still need to have inputs on your form you can do something like this:
const handleSubmit = e => {
e.preventDefault();
const inputs = Object.values(e.target)
.filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
setFormVals({ ...formVals, ...inputs });
}
See the demo below:
const Demo = () => {
const [formValues] = React.useState({});
const handleSubmit = e => {
e.preventDefault();
const inputs = Object.values(e.target)
.filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
console.log(inputs);
}
return (
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" value={formValues.name} />
<input name="email" placeholder="Email" value={formValues.email} />
<input name="hiddenInput" value="hiddenValue" type="hidden" />
<button type="submit">Submit</button>
</form>
);
}
ReactDOM.render(<Demo />, document.getElementById('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
If you know what the inputs that you need you can do something like this:
const Demo = () => {
const formRef = React.useRef(null);
const [formValues, setFormValues] = React.useState({});
const handleChange = e => {
setFormValues({
...formValues,
[e.target.name]: e.target.value,
});
}
const handleSubmit = e => {
e.preventDefault();
setFormValues({ ...formValues, hiddenInput: formRef.current.hiddenInput.value });
}
return (
<form onSubmit={handleSubmit} ref={formRef}>
<input name="name" placeholder="Name" value={formValues.name} onChange={handleChange} />
<input name="email" placeholder="Email" value={formValues.email} onChange={handleChange} />
<input name="hiddenInput" value="hiddenValue" type="hidden" />
<button type="submit">Submit</button>
<pre>{JSON.stringify(formValues, null, 2)}</pre>
</form>
);
}
ReactDOM.render(<Demo />, document.getElementById('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
Answering your questions:
Since you know how to use component's state you may set the value as : <input type='text' value={this.state.foo} /> or even via props passing <input type='hidden' value={this.props.foo} />
You don't need to serialise anything at all. Use your component's local state or even a state container like Redux or Flux in order to pick the appropriate data. Take a look at this fairly simple example:
var SuperForm = React.createClass({
getInitialState() {
return {
name: 'foo',
email: 'baz#example.com'
};
},
submit(e){
e.preventDefault();
console.log("send via AJAX", this.state)
},
change(e,key){
const newState = {};
newState[key] = e.currentTarget.value;
this.setState(newState)
},
render: function() {
return (
<div>
<label>Name</label>
<input
onChange={(e) => this.change(e,'name')}
type="text"
value={this.state.name} />
<label>Email</label>
<input
onChange={(e) => this.change(e,'email')}
type="text"
value={this.state.email} />
<button onClick={this.submit}>Submit</button>
</div>
);
}});
Demo
AJAX is a set of web development techniques while Axios is a JavaScript framework. You may use jQuery, Axios or even vanilla JavaScript.
Trying to get the send data inside an Wordpress plugin but I cant get the data to work. So how do I get the data from the serialized part inside a php file?
// the code
<form method="post" id="form-settings" action="ajaxpro.php" >
<?php wp_nonce_field( 'settings', 'settings_nonce', false );?>
<input name="field-one" type="text"/>
<input name="field-two" type="text"/>
<textarea name="field_three">Hello world</textarea>
// notice the double fields
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<input name="field-x[]" type="text"/>
<button id="submitme" name="save-form">Save</button>
</form>
$('body').on('submit', '#form-settings', function(e){
var seri =$(this).serializeArray()
$.post(ajaxurl, {
action: 'save_ajax_func',
posted: seri
}, function(response) {
console.log( response );
});
return false;
});
//notice that I do use double field names(field-x)
echo $_POST[ 'posted' ][ 'field-one' ] // not working
To use the [] notation in the html it would be posted[field-x]
<input name="posted[field-x]" type="text"/>
the ajax will have to change to below
var seri = $(this).serializeArray();
seri.push({name:'action',value:'save_ajax_func'});
$.post(ajaxurl, seri, function(response) {
console.log( response );
});
Please, I need help in passing the check box value through ajax to other php file
This is my form :
<form class="form-horizontal" onsubmit="Javascript:return validate();" method="post" id="form">
<b>Jawwal Number</b>
<input name="msisdn" type="text" id="msisdn" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Username</b>
<input name="username" type="text" id="username" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Add Extra Security (Activation Code)</b>
<input type="checkbox" name="security" id="security">
<input type="submit" value="submit" class="btn btn-primary">
</form>
And this is my Ajax code :
$("#form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* set all the vars you want to post on here */
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
**'security':$('input[name="security"]').val(),**
'submit': $('input[name="submit"]').val()
};
$.ajax({
url: '/bulk2/admin/process/add_user.php',
method:'POST',
data: parameters,
success: function(msg) {
$('#test').append(msg);
}
})
});
What should I do so that I can pass the checkbox value to the other page ?
You can also use checkbox checked method.
var security = $('input[name="security"]').prop('checked'); /* it will return true or false */
and update your code
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
'security':security,
'submit': $('input[name="submit"]').val()
};
Use the method is() with property :checked.
var parameters = {
'security':$('input[name="security"]').is(':checked'),
};
This works for me.
Have a good day.
I am doing a select all checkbox to delete selected posts. I am able to get the result in the jquery but I am not sure how to use that result to process in my Codeigniter Controller. Maybe someone can enlighten me. Thanks!
View File:
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value="" onClick="return confirm('Delete selected posts?')"><i class="icon-trash icon-white"> </i> Delete Selected</button>
JQuery:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selected").click(function(event) {
/* stop form from submitting normally */
event.preventDefault();
var values = new Array();
$.each($('input[name="delete_selection[]"]:checked'), function() {
var delete_selection = $(this).val()
console.log(delete_selection);
});
});
Controller:
public function post_delete(){
//HOW TO GRAB THE RESULT FROM THE JQUERY?
//I KNOW IT SHOULD BE IN AJAX BUT NOT QUITE SURE HOW TO DO IT.
$id = $this->input->post('delete_selection');
for( $i=0; $i<sizeof($id); $i++) :
$this->posts_model->delete_post_selection($id[$i]);
endfor;
$data['message_success'] = $this->session->set_flashdata('message_success', 'You have successfully deleted your selected posts.');
redirect('admin/posts/posts_list', $data);
}
Model:
//MULTIPLE DELETE
function delete_post_selection($id) {
$this->db->where_in('post_id', $id)->delete('posts');
return true;
}
Your thinking is wrong, the controller isn't gonna 'grab' the values. But javascript is going to post to the controller
Assuming you put your html inside a form you could do something like this:
view:
<form action="/post_delete">
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value=""><i class="icon-trash icon-white"> </i> Delete Selected</button>
</form>
JS:
$('#delete_selection').click(function(e){
if(!confirm('Delete?')) return;//ask user if they're sure
//stop default form submitting from happening because
//we'll use ajax
e.preventDefault();
var form = $(this).closest('form');//get the parent form
$.ajax({
url: form.attr('action'),//get url to send it to
type: "POST",
data: form.serialize(),//get data from the form
success: function(){
//do something with success
}
error: function(){
//do something with error
}
});
And now you can use the data in your controller by accessing $_POST try
var_dump($_POST);
to see what has been posted
I am not sure if this is the correct way as it POST repeatedly but does the work so far.
In my JS:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selection").click(function(event) {
if(!confirm('Delete selected posts?')) return false;//ask user if they're sure
/* stop form from submitting normally */
event.preventDefault();
$.each($('input[name="delete_selection[]"]:checked'), function() {
$.ajax({
type: "POST",
url: 'post_delete_selection',
data:
{ selected: $(this).val() },
success: function(data){
setTimeout(function () {
window.location.href = window.location.href;
}, 1000);
$('#ajax_message').show().html('Successfully deleted.');
},
});
});
});
My Controller:
public function post_delete_selection(){
$selectedIds = $_POST['selected']; //THIS GRABS THE VALUES FROM THE AJAX
$this->posts_model->delete_post_selection($selectedIds);
}
My Model:
function delete_post_selection($selectedIds) {
$this->db->where_in('post_id', $selectedIds)->delete('posts');
return true;
}