Ajax form not submitting form rails - javascript

I'm using a super basic google form on my website. I'm using this website to extract the HTML to display it on my website - http://stefano.brilli.me/google-forms-html-exporter/
Once I hit submit, nothing happens. The page is just locked. I'm trying to resubmit it to another page. Here is my code
<div class="row">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSfJQ9EkDN8aggSL9AEB2PK4BGiZgBzLDbS1IPppfSkU1zy-oA/formResponse"target="_self" id="bootstrapForm" method="POST">
<div class="col-sm-6 col-md-3">
<input id="679075295" type="text" name="entry.679075295" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="897968244" type="text" name="entry.897968244" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="685661947" type="text" name="entry.685661947" class="form-control" >
</div>
<input id="503500083" type="hidden" name="entry.503500083" value="<%= #investment.id %>" >
<div class="col-sm-6 col-md-3">
<button type="submit" value"submit" class="btn btn--primary type--uppercase" >Get Started</button>
</div>
</form>
Here is the ajax script
<script>
$('#bootstrapForm').submit(function (event) {
event.preventDefault()
var extraData = {}
$('#bootstrapForm').ajaxSubmit({
data: extraData,
dataType: 'jsonp', // This won't really work. It's just to use a GET instead of a POST to allow cookies from different domain.
error: function () {
// Submit of form should be successful but JSONP callback will fail because Google Forms
// does not support it, so this is handled as a failure.
alert('Form Submitted. Thanks.')
// You can also redirect the user to a custom thank-you page:
window.location = 'http://reif.com.au/thankyou'
}
})
})
</script>
</div>

Feeling a little silly on this one. Essentially i didn't copy over all of the scripts. I was rushing through.. ALWAYS number 1 error!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha256-2Pjr1OlpZMY6qesJM68t2v39t+lMLvxwpa8QlRjJroA=" crossorigin="anonymous"></script>
This is what i needed to add, it now successfully submits and redirects!

Related

keep properties after jquery.load

I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question

jqWidgets: How can I post an HTML form inside a jqxWindow?

I created the following HTML form inside a jqxWindow widget for a Laravel project:
<div id="provinceWindow">
<div id="provinceWindowHeader"></div>
<div id="provinceWindowContent">
<form id="provinceForm" method="POST" action="{{route('province.store')}}">
{{ csrf_field() }}
<input type="hidden" name="provinceId" id="provinceId" value=""/>
<div class="form-group row">
<div class="col-6"><label>English province name</label></div>
<div class="col-6"><input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20"/></div>
</div>
<div class="form-group row">
<div class="col-6"><label>Spanish province name</label></div>
<div class="col-6"><input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20"/></div>
</div>
<br/>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3" />
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3" />
</div>
</form>
</div>
</div>
This is the javascript file:
$(document).ready(function () {
var datarow = null;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
//-----------------------------
// Window settings
//-----------------------------
$('#provinceWindow').jqxWindow({
autoOpen: false,
isModal: true,
width: 400,
height: 160,
resizable: false,
title: 'Province name',
cancelButton: $('#cancelBtn'),
initContent: function () {
$('#submitBtn').jqxButton();
$('#submitBtn').on('click', function () {
$('#provinceForm').submit();
});
}
}).css('top', '35%');
The file routes\web.php has only one resourse route defined for this page:
// Routes for province maintenance
Route::resource('province', 'provinceController');
Checking the available routes with php artisan route:list command, I get these:
Method URI Name Action
GET|HEAD / APP\Http\Controllers\homeController#index
GET|HEAD province province.index APP\Http\Controllers\provinceController#index
POST province province.store APP\Http\Controllers\provinceController#store
GET|HEAD province/create province.create APP\Http\Controllers\provinceController#create
GET|HEAD province/{province} province.show APP\Http\Controllers\provinceController#show
PUT|PATCH province/{province} province.update APP\Http\Controllers\provinceController#update
DELETE province/{province} province.destroy APP\Http\Controllers\provinceController#destroy
GET|HEAD province/{province}/edit province.edit APP\Http\Controllers\provinceController#edit
My controller action:
public function store(Request $request)
{
$fields = $request->all();
if ($request->provinceId == '') {
$province = new province($fields);
$validator = Validator::make($fields, $province->rules());
if ($validator->fails()) {
return redirect('')->withErrors($validator)->withInput();
}
else {
$province->save();
}
return view('province/index');
}
}
The form is shown on top of a jqxGrid widget, as a modal window, in order to capture the required information and perform the CRUD operations for the corresponding DB table.
The problem is, when I click the "Submit" button the window is closed and nothing else happens. The form is not posted to the indicated action and the data entered get lost.
It does not matter if I initialize the submitBtn inside the initContent or outside of it. The form is never posted.
I also tried the Close event of the jqxWindow to no avail.
If I take a look to the generated HTML it looks like this:
<form id="provinceForm" method="POST" action="http://mis:8080/province">
<input type="hidden" name="_token" value="Y9dF5PS7nUwFxHug8Ag6PHgcfR4xgxdC43KCGm07">
<input type="hidden" name="provinceId" id="provinceId" value="">
<div class="form-group row">
<div class="col-6">
<label>English province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20">
</div>
</div>
<div class="form-group row">
<div class="col-6">
<label>Spanish province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20">
</div>
</div>
<br>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3 jqx-rc-all jqx-button jqx-widget jqx-fill-state-normal" role="button" aria-disabled="false">
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3">
</div>
</form>
Pressing the submit button takes me to the home page and nothing gets added to the DB table.
I guess the issue has something to do with Laravel routes because I get no errors.
What is missing or what is wrong with this approach?
Any light is appreciated.
Alright, because I erroneously added in my Model a validation, that was not needed, for a column (there was already a constraint defined at the DB table level), it was not possible to fulfill the validator when saving a new record. I commented that line in my Model and, that was it!
protected $rules = array(
'provinceNameEn' => 'required|alpha|max:20',
'provinceNameSp' => 'required|alpha|max:20'
//'deleted' => 'required|in:M,F' // This is already validated in a DB constraint.
);
I noticed the control was returned to my home page but without any message or error, but if you pay attention to my controller it was precisely the behavior programmed. However, there is no implementation to display the error messages, so I added dd($validator); before that return statement. There I read the message and finally found the solution.

AJAX form submission not reloading content

I have seen quite a few questions and answers on here but none seem to fix my issue. I have a form which is loaded from a ajax load call into a div class called dynamic-content. Basically if the form submit button is pressed I want it to reload this form in ajax so that it does the php form validation. My issue is that when the submit occurs I call the ajax load to reload via javascript but it is not triggering and instead its just going back to the current index page. My JS is as follows:
$(document).ready(function () {
//Handle AJAX request from sidebar buttons
var trigger = $('.submit-btn'),
container = $('.dynamic-content');
$(".add-customer-form-btn").submit(function() {
// do something...
alert('test');
container.load('customers/customersaddform.php',$("form").serializeArray());
return false;
});
});
my html form in customersaddform.php which is loaded into dynamic-content div in located main index file.
<?php
//FORM VALIDATION CHECKS
?>
<form action="" method="post">
<div class="form-field add-customer-form">
<div class="container-fluid">
<!-- Stack the columns on mobile by making one full-width and the other half-width -->
<h4>Account Information</h4>
<div class="row">
<div class="col-md-6 label-container">
<div class="input-group input-group-icon">
<input type="text" placeholder="First Name" name="first-name" required/>
<div class="input-icon"><i class="fa fa-user"></i></div>
<div class="input-error-msg"><?php echo $first_name_err;?></div>
</div>
</div>
<div class="row">
<div class=col-md-12 label-container">
<input type="submit" class="add-customer-form-btn submit-btn" value="Submit">
</div>
</div>
</div>
</div>
</form>

Razor form on a facebook tab page

I am trying to execute a form inside an Facebook tab. What have I tried among many things:
It seems like Request.HttpMethod == "POST" is not working as usual. #message prints out on pageload.
I have tried to add alert to before return $('form').valid(). This is not being executed.
Any ideas of issue or another workaround.
Code:
#{
var message = string.Empty;
if (Request.HttpMethod == "POST")
{
message = "SUBMITTED";
}
}
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<div class="form">
#if (!string.IsNullOrEmpty(message))
{
<p class="formFinish">
#message
</p>
}
<div class="row">
<label>Name</label>
<input type="text" name="Name" id="Name" class="required" minlength="4" maxlength="30" />
</div>
<div class="newGame row">
<button class="btn">Submit</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('form').attr('enctype', "multipart/form-data");
$('form').on('submit', function () {
return $('form').valid()
});
});
</script>
I might be missing something obvious, it doesn't seem that you're sending a post. You've got no actual form there, just a div with the class of "form", and your "Submit" button is just a button that doesn't appear to have any action associated with it. You're going to need to actually post something if you want the page to get a post request.
EDIT: Here's working code, I just had to change your "div class='form'" into an actual form element with method "post". Note that I didn't fix your usage of jQuery validate, but now that the form is actually generating a post request, you should be well on your way.
#{
var message = string.Empty;
if (Request.HttpMethod == "POST")
{
message = "SUBMITTED";
}
}
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<form method="post">
#if (!string.IsNullOrEmpty(message))
{
<p class="formFinish">
#message
</p>
}
<div class="row">
<label>Name</label>
<input type="text" name="Name" id="Name" class="required" minlength="4" maxlength="30" />
</div>
<div class="newGame row">
<input type="submit" class="btn" value="Submit" />
</div>
</form>

Sending HTML form via AJAX to PHP server

I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html

Categories

Resources