Angular Form Trouble Binding to Scope - javascript

I have a simple Angular form with a textbox and some hidden fields. This form is recycled many times on my page.
<form accept-charset="UTF-8" name="form.jobAppForm" class="pitch-form" novalidate>
<div style="display:none;">
<input name="authenticity_token" type="hidden" ng-value="window._token">
<input name="user_id" type="hidden" ng-value="<%= current_user.id %>">
<input name="job_description_id" type="hidden" ng-value="j.id">
<input name="company_id" type="hidden" ng-value="j.company_id">
</div>
<div class="form-group">
<textarea class="apply-textbox" id="pitch" name="pitch" ng-model="jobApp.pitch"></textarea>
</div>
<input class="apply-submit-btn" name="commit" type="submit" value="Submit Application" ng-click="createApplication(jobApp)" onClick="this.disabled=true;this.value='Sending…';">
</form>
In my controller I have a newApplication method that initializes $scope.jobApp and then a createApplication method that sends a post request to the server. If I log the value of $scope.jobApp when createApplication is called, all the attributes are still set to null. Only the pitch attribute seems to be bound. If I enter a pitch, that is bound to the scope, but nothing else is. I'm not sure what I'm missing. Why is pitch bound but none of the other attributes? Here are my controller methods.
$scope.newApplication = function() {
console.log('new app')
$scope.form = {}
$scope.jobApp = {
token: null,
user_id: null,
job_description_id: null,
company_id: null,
pitch: null
};
};
$scope.createApplication = function() {
var jobAttributes = $scope.jobApp;
console.log(jobAttributes)
if ($scope.form.jobForm.$valid) {
$http({
method: 'POST',
url: '/applications',
data: jobAttributes,
headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}
}).success(function(data, status){
console.log('success');
}, function(err){
alert("Failed to save job! Server responded with: " + err)
});
};
}
Note: I've tried setting ng-model="jobApp.attribute" for the other attributes as well as using value= rather than ng-value= to no effect.

like #HaukurHaf, you need to use ng-model on the form field.
<form accept-charset="UTF-8" name="form.jobAppForm" class="pitch-form" novalidate>
<div style="display:none;">
<input name="authenticity_token" type="hidden" ng-model="jobApp.token">
<input name="user_id" type="hidden" ng-model="jobApp.user_id">
<input name="job_description_id" type="hidden" ng-model="jobApp.job_description_id">
<input name="company_id" type="hidden" ng-model="jobApp.company_id">
</div>
<div class="form-group">
<textarea class="apply-textbox" id="pitch" name="pitch" ng-model="jobApp.pitch"></textarea>
</div>
<input class="apply-submit-btn" name="commit" type="submit" value="Submit Application" ng-click="createApplication(jobApp)" onClick="this.disabled=true;this.value='Sending…';">

Related

How do I automatically submit two forms without the page refreshing?

<form id="addToCart" action="http://my-website/cart/action.php">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
document.forms[1].submit();
</script>
This only submits the first form but not the second. How can I get it to submit both?
Before anyone asks, I also tried this below and it still didn't work.
document.getElementById("addToCart").submit();
document.getElementById("buy").submit();
In order of preference
Submit all data to action and have that add AND buy
Use ajax, submit the second form in the success of the first submit
const url = "https://my-website/cart/action.php";
document.getElementById("container").addEventListener("click", e => {
const itemNum = e.target.dataset.itemnum;
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
action: "add",
itemNum: itemNum
})
})
.then(() => {
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
action: "buy",
itemNum: itemNum
})
})
})
});
<div id="container">
<input type="button" data-itemnum="201" value="Buy 201 with one click " />
<input type="button" data-itemnum="202" value="Buy 202 with one click " />
<input type="button" data-itemnum="203" value="Buy 203 with one click " />
</div>
Two iframes (don't change the fields or methods, only the value of action):
<form id="addToCart" method="post" action="http://my-website/cart/action.php" target="iframe1">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php" method="POST" target="iframe2">>
<input type="hidden" name="action" value="buy" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<iframe name="iframe1"></iframe>
<iframe name="iframe2"></iframe>
<script>
document.forms[0].submit();
setTimeout(() => document.forms[1].submit(),2000);
</script>
This would be my approach. Use jquery ajax to define a .submit() function for each form (the procedure to follow when submitted). Use .click() to "click" both submit buttons programmatically. Then use return false to prevent page refresh. This should submit both forms simultaneously. I was unable to test this without the php actions.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addToCart" action="http://my-website/cart/action.php" method="get">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="post">
<input type="submit" value="Submit request" />
</form>
<script>
$(document).ready(function() {
const $addToCartForm = $("#addToCart");
const $buyForm = $("#buy");
const addToCartUrl = $("#addToCart").attr("action");
const buyUrl = $("#buy").attr("action");
$buyForm.submit(function() {
$.ajax({
url: buyUrl,
type: $buyForm.attr("method"),
data: $buyForm.serialize()
});
return false;
});
$addToCartForm.submit(function() {
$.ajax({
url: buyUrl,
type: $addToCartForm.attr("method"),
data: $addToCartForm.serialize()
});
return false;
});
$addToCartForm.find("[type='submit']").click();
$buyForm.find("[type='submit']").click();
});
</script>
you can use AJAX with JQuery $.post() method for submitting both forms simultaneously.
$(document).ready(main);
function main(){
submitFormUsingAjax('#addToCart');
submitFormUsingAjax('#buy');
}
function extractInputDataOfFromRef(formSelector){
var $inputRefs = $(formSelector +' input:not([type=submit])');
var data = {};
$inputRefs.each(function($index){
var name = $(this).attr("name");
var value = $(this).attr("value");
data[name] = value;
})
return data;
}
function submitFormUsingAjax(formSelector){
var $formRef = $(formSelector);
var url = $formRef.attr('action');
var data = extractInputDataOfFromRef(formSelector);
var method = $formRef.attr('method');
method = method && method.toUpperCase();
var posting;
if(method == 'GET'){
posting = $.get(url,data);
}else{
posting = $.post(url,data)
}
posting.done(function(response) {
console.log("form submitted: ",response);
});
posting.fail(function(error) {
console.log("form submittion failed:",error.statusText);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addToCart" action="http://my-website/cart/action.php" method="get">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
<input type="submit" value="Submit request" />
</form>
document.forms[0].onsubmit = (e) => {
e.preventDefault();
}

FormData Returning Undefined in Ajax and Wordpress Form

I created a contact form for a Wordpress theme (custom) using jQuery/Ajax. When I tested the wp_send_json_sucess with "it works" it returned as suspected. However, when I added $formdata and the name of a field on the form the from returned undefined in the JS alert box. I'm pretty sure I've typed it correctly, as I was following this tutorial: https://www.youtube.com/watch?v=LYvx_L9ESn0. But I cannot seem to get it to work.
Code for functions.php here
add_action('wp_ajax_contact', 'contact_form');
add_action('wp_ajax_nopriv_contact', 'contact_form');
function contact_form()
{
$formdata = [];
wp_parse_str( $_POST['contact'], $formdata );
wp_send_json_success( $formdata ['myName'] );
}
Form Code Here :
<form id="contact">
Name: <input type="text" name="myName" class="contactform
fields" placeholder="name"required><br><br>
Email: <input type="text" name="myEmail" class="contactform
fields" placeholder="you#youremail.com" required><br><br>
<p>What is your inquiry regarding?</p><be>
<input type="radio" name="reason" value="general">
<label for="news">General Inquiry</label><be>
<input type="radio" name="reason" value="course">
<label for="news">Courses</label><br>
<p class="contact_txt">Your Message:</p>
<textarea name="msg" rows="5" cols="700" placeholder="begin
typing message here..." required>
</textarea>
<p class="contact_txt">Would you like to subscribe to our
newsletter?</p>
<br>
<input type="checkbox" name="news" value="Subscribe">
<label for="news">Yes, I would like to subscribe</label>
<br>
<input class="btns" name="btn-send" id="mySubmit" type="submit" value="submit">
<input class="btns" name="btn-reset" id="myReset" type="reset" value="reset">
</form>
Script Here :
<script>
jQuery('#contact').submit( function(event){
event.preventDefault();
var endpoint = '<?php echo admin_url('admin-ajax.php' ); ?>';
var form = jQuery('#contact').serialize();
var formdata = new FormData;
formdata.append('action', 'contact');
formdata.append('contact', 'form');
jQuery.ajax(endpoint, {
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function(res){
alert(res.data);
},
error:function(err){
}
})
})
</script>

casperjs - fill form / post form - solving death by captcha

have that simple Webform which i want to fill and than get text from the result page.
<html><head></head><body><table><tr><td>
<form method="post" action="http://api.dbcapi.me/decaptcher"
enctype="multipart/form-data">
<input type="hidden" name="function" value="picture2">
<input type="text" name="username" value="">
<input type="text" name="password" value="">
<input type="file" name="pict">
<input type="text" name="pict_to" value="0">
<input type="text" name="pict_type" value="0">
<input type="text" name="print_format" value="html">
<input type="submit" value="Send">
</form>
</td></tr></table></body></html>
And just want to Post 3 Values to the Form. I tried with the following examples:
casper.start('http://api.dbcapi.me/decaptcher?function=picture2&print_format=html', function() {
this.fillSelectors('#html>body>table>tbody>tr>td>form', {
'input[name="username"]': 'loginname',
'input[name="password"]': 'password',
'input[name="pict"]': 'folder/file.jpeg'
}, true);
});
or:
casper.open('http://api.dbcapi.me/decaptcher?function=picture2&print_format=html', {
method: 'post',
data: {
'username': 'loginname',
'password': 'passwortd',
'pict': 'folder/file.jpeg'
},
headers: {
'Content-type': 'multipart/form-data'
}
});
and
casper.start('http://api.dbcapi.me/api/captcha', function() {
this.fill('form', {
'username': 'loginname',
'password': 'passwort',
'captchafile': 'folder/file.jpeg',
}, true);
});
none of them work correct :-(

Upload input don't work when AJAX is invoked [duplicate]

I've a <form> to upload an image and a <fieldset> to send some data using AJAX, they both work fine, but my problem happens when I try to merge them in one form. I'm using Node.JS server.
Upload <form>:
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="upl"/>
<input type="submit" value="Send"/>
</form>
Node.JS router upload post:
router.post('/upload', upload, function (req, res, next) {
console.log(req.file);
res.status(204).end();
});
<fieldset>:
<div id="addAdv">
<fieldset class="form-group">
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<button id="btnAddAdv" type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</div>
Node.Js router data post:
router.post('/addadv', function(req, res) {
Feed.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
AJAX:
$('#btnAddAdv').on('click', addAdv);
function addAdv(event) {
.....
$.ajax({
type: 'POST',
data: newUser,
url: '/addadv',
dataType: 'JSON'
}).done(function( response )...}
Let's try to merge them:
<div id="addAdv">
<form method="post" enctype="multipart/form-data" action="upload">
<fieldset class="form-group">
<input type="file" name="upl"/>
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<input type="submit" id="btnAddAdv" value="Send"/>
</fieldset>
</form>
</div>
Also tried:
<button id="btnAddAdv" type="submit">Send</button>
If you're submitting your merged form via the submit button and not via XHR, then you need to add name attributes for your non-file fields, otherwise the browser will not send them to the server.

Merging form and fieldset doesn't work?

I've a <form> to upload an image and a <fieldset> to send some data using AJAX, they both work fine, but my problem happens when I try to merge them in one form. I'm using Node.JS server.
Upload <form>:
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="upl"/>
<input type="submit" value="Send"/>
</form>
Node.JS router upload post:
router.post('/upload', upload, function (req, res, next) {
console.log(req.file);
res.status(204).end();
});
<fieldset>:
<div id="addAdv">
<fieldset class="form-group">
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<button id="btnAddAdv" type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</div>
Node.Js router data post:
router.post('/addadv', function(req, res) {
Feed.collection.insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});
AJAX:
$('#btnAddAdv').on('click', addAdv);
function addAdv(event) {
.....
$.ajax({
type: 'POST',
data: newUser,
url: '/addadv',
dataType: 'JSON'
}).done(function( response )...}
Let's try to merge them:
<div id="addAdv">
<form method="post" enctype="multipart/form-data" action="upload">
<fieldset class="form-group">
<input type="file" name="upl"/>
<label for="inputTimeStamp">Time</label>
<input id="inputTimeStamp" type="text" class="form-control"/><br/>
<label for="inputURL">URL</label>
<input id="inputURL" type="url"/><br/>
<input type="submit" id="btnAddAdv" value="Send"/>
</fieldset>
</form>
</div>
Also tried:
<button id="btnAddAdv" type="submit">Send</button>
If you're submitting your merged form via the submit button and not via XHR, then you need to add name attributes for your non-file fields, otherwise the browser will not send them to the server.

Categories

Resources