Php form creates many empty lines associates with js event handler - javascript

I created a php form that works well.
BUT, (yes there is always a BUT) I handle the submit event to call a link that insert datas in another database.
When Js run, my form creates a lot of empty lines in my personal database. I don't understand why.
I give you my code :
PHP :
public function displayForm() {
$output = '<div id="form-popup-newsletter">
<center>
<form id="nl_form" method="post">
<legend>Abonne-toi à la Newsletter<span id="cross-close">X</span></legend>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input id="civility" type="radio" name="civility" value="madame"> Madame
</label>
<label class="btn btn-primary">
<input id="civility" type="radio" name="civility" value="monsieur"> Monsieur
</label>
</div>
<div>
<label for="surname">Prenom</label>
<input id="surname" type="text" name="surname" value="Surname" />
<span id="w-surname"></span>
</div>
<div>
<label for="name">Nom</label>
<input id="name" type="text" name="name" value="Name"/>
<span id="w-name"></span>
</div>
<div>
<label for="birthdate">Date de Naissance</label>
<input id="birthdate" type="date" name="birthdate" value="Date de naissance"/>
<span id="w-birthdate"></span>
</div>
<div>
<label for="mail">Email</label>
<input id="mail" type="email" name="mail" value="Email"/>
<span id="w-mail"></span>
</div>
<div>
<label for="postal_code">Code Postal</label>
<input id="postal_code" type="number" name="postal_code" value="Code Postal"/>
<span id="w-postal_code"></span>
</div>
<input id="#submitform" type="submit" name="submitform" value="Sauvegarder" class="btn btn-danger" /> </form>
</center>
</div>';
$objForm = new CustomForm;
if ( isset( $_POST['submitform'] ) ) {
if (isset($_POST['civility'])) {
$objForm->civility = $_POST['civility'];
}
$objForm->surname = $_POST['surname'];
$objForm->name = $_POST['name'];
$objForm->birthdate = $_POST['birthdate'];
$objForm->mail = $_POST['mail'];
$objForm->postal_code = $_POST['postal_code'];
}
$this->fillDB($objForm);
$this->context->smarty->assign(array(
'output' => $output
));
}
Javascript :
$("#nl_form").submit(function(e){
e.preventDefault();
var civility = $('#civility').val();
var surname = $('#surname').val();
var name = $('#name').val();
var birthdate = $('#birthdate').val();
var mail = $('#mail').val();
var postal_code = $('#postal_code').val();
window.open("http://mylink.com/register.php?inp_46="+civility+"&inp_1="+surname+"&inp_2="+name+"&inp_4="+birthdate+"&inp_3="+mail+"&inp_13="+postal_code+"");
return true;
});
Best.

When you open a link with window.open then you make a HTTP GET Request. So you have to use $_GET[...] to get the value of your parameters. E.g. for surname $_GET["inp_1"].
But don't use window.open for that instate make a Ajax request.
Here some usefull links
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://jquery.com/ http://api.jquery.com/jQuery.post/

Related

Having problem submitting a form without reload using jquery ajax

When i submit form it doesnot update value in database mysql.Its a form written in php.
here is my php and html. I want that the form should not reload and it must submit the changes in database without reloading the page and show preloader for 1 sec on submitting form.
HTML,PHP AND ACTION of form: Here action is the current page where this form is avalilable
detail_customer.php
<?php
$server = "localhost";
$username = "root";
$pass = "";
$dbname = "stinkspolitics_pl";
$conn = mysqli_connect($server, $username, $pass, $dbname);
if (isset($_GET['detail_customer'])) {
$quest_id = $_GET['detail_customer'];
$get_quest = "SELECT * FROM questions WHERE quest_id = '$quest_id'";
$getting_quest = mysqli_query($conn, $get_quest);
while ($row = mysqli_fetch_assoc($getting_quest)) {
$quest_title = $row['quest_title'];
$category_id = $row['category_id'];
}
}
if (isset($_POST['submit'])) {
$quest_t = $_POST['quest_t'];
$update = "UPDATE questions SET quest_title = '$quest_t' WHERE quest_id = '$quest_id'";
$run_update = mysqli_query($conn, $update);
if ($run_update) {
echo 'hello';
}
}
?>
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php
" method="POST" class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<?php echo $category_id ?>" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<?php echo $quest_title ?>" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
JS Code
index.js
$("#form-submit").on("submit", function () {
// e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: formData,
success: function (data) {
$(".alert-success").show();
$(".alert-success").fadeOut(4000);
console.log(data);
},
error: function (data) {
$(".alert-danger").show();
$(".alert-danger").fadeOut(4000);
console.log(data);
},
});
return false;
});
Ajax Success Response But not updating data in mySQL
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php" method="POST"
class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<br />
<b>Warning</b>: Undefined variable $category_id in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>62</b><br />
" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<br />
<b>Warning</b>: Undefined variable $quest_title in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>66</b><br />
" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
The condition if (isset($_POST['submit'])) { will never evaluate to true, since there is no input element in the form with name="submit" (the button with name='submit' does not send the attribute by default).
Either change the condition:
if (isset($_POST['quest_t'])) { ...
Or, include an input element with name='submit', for example:
<input name="submit" type="hidden" />
Also, make sure to move the $_POST check at the beginning of the file and ensure that no other code will be evaluated in the PHP file (e.g. the rest of the HTML code) if a POST request has been received.
Just return false after at the end of the method.
jQuery has its own way of ensuring "preventDefault()" and it is just returning false from the submit handler.
Full background on this here:
event.preventDefault() vs. return false
Issue has been solved. By changing path and then putting path of js file again.

Storing HTML Form input as an Object using a Constructor class and a dynamic variable name (Plain JS)

<form id="projectForm" onsubmit="return ptitle.value = new Project(this);">
<div class="form-row">
<label for="ptitle">Title: </label>
<input type="text" id="ptitle" name="ptitle"><br>
</div>
<div class="form-row">
<label for="pdescription">Discription: </label>
<input type="text" id="pdescription" name="pdescription"><br>
</div>
<div class="form-row">
<label for="pdueDate">Due Date</label>
<input type="date" id="pdueDate" name="pdueDate"><br>
</div>
<div class="form-row">
<label for="high">High</label>
<input type="radio" id="high" name="priority">
<label for="low">Low</label>
<input type="radio" id="low" name="priority"><br>
<input id="submit" type="submit" value="submit">
</div>
</form>
So I would like to take the data submitted from this form and call a constructor method within the Projects class. I'd also like to be able to dynamically generate the variable name from the title value of the form. Here's the JavaScript code. I'll need to use plain JS as that is what's required for the project! We're also required to use a constuctor class or factory function to generate the projects. As you can see I've tried to take a stab at it but unfortunately it hasn't worked. Thanks in advance.
class Project {
constructor(form) {
this.title = form.ptitle.value;
this.description = form.pdescription.value;
this.dueDate = form.pdueDate.value;
this.priority = form.priority.value;
}
todoList = {};
addTodoList(value, description) {
this.todoList[value] = description;
}
removeTodoList(key) {
delete this.todoList[key];
}
}
Thanks again!!!
I'd also like to be able to dynamically generate the variable name from the title value of the form That sounds like a terrible idea...
Well here you go
class Project {
constructor(form) {
this.title = form.ptitle.value;
this.description = form.pdescription.value;
this.dueDate = form.pdueDate.value;
this.priority = form.priority.value;
}
todoList = {};
addTodoList(value, description) {
this.todoList[value] = description;
}
removeTodoList(key) {
delete this.todoList[key];
}
}
<form id="projectForm" onsubmit="window[ptitle.value] = new Project(this);return false">
<div class="form-row">
<label for="ptitle">Title: </label>
<input type="text" id="ptitle" name="ptitle"><br>
</div>
<div class="form-row">
<label for="pdescription">Discription: </label>
<input type="text" id="pdescription" name="pdescription"><br>
</div>
<div class="form-row">
<label for="pdueDate">Due Date</label>
<input type="date" id="pdueDate" name="pdueDate"><br>
</div>
<div class="form-row">
<label for="high">High</label>
<input type="radio" id="high" name="priority">
<label for="low">Low</label>
<input type="radio" id="low" name="priority"><br>
<input id="submit" type="submit" value="submit">
</div>
</form>

ng-model not updating my object values

I have a one-page application using angularJS.
I have in my controller a user object defined like this :
this.user = {
'name':'Robert',
'age':'30'
}
I made a form to update those informations prefilled with those user's informations on my page such like this :
<form name="userForm" ng-submit="userForm.$valid && pageCtrl.userForm(user)" novalidate>
<label for="name">Name *</label>
<input type="text" name="name" ng-model='pageCtrl.user.name' class="form-control" required/>
<label for="age">Age *</label>
<input type="text" name="age" ng-model='pageCtrl.user.age' class="form-control" required/>
<span ng-if='!userForm.$valid' class="error">Invalid form</span>
<input type="submit" value="Save my informations" class="btn btn-success"/>
</form>
My problem is the following : in the header bar of the page the username is displayed ({{pageCtrl.user.name}}).
When the user acts on the form by changing his name, this is updating before the form is saved.
I'd like to wait for the form submission to see the username updated. But i still want to get my form prefilled with user's informations.
Do you have any idea about how to do this?
Thank you by advance
You can use a copied object to only apply the changes when the user save the form :
var app = angular.module('app', []);
app.controller('pageCtrl', function() {
var vm = this;
vm.user = {
'name':'Robert',
'age':'30'
};
vm.tmpUser = {};
vm.update = function() {
vm.user = angular.copy(vm.tmpUser);
};
vm.reset = function() {
vm.tmpUser = angular.copy(vm.user);
};
vm.reset();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="pageCtrl as pageCtrl">
<form name="userForm" ng-submit="userForm.$valid" novalidate>
<label for="name">Name *</label>
<input type="text" name="name" ng-model='pageCtrl.tmpUser.name' class="form-control" required/>
<label for="age">Age *</label>
<input type="text" name="age" ng-model='pageCtrl.tmpUser.age' class="form-control" required/>
<span ng-if='!userForm.$valid' class="error">Invalid form</span>
<input type="submit" ng-click="pageCtrl.update()" ng-disabled="!userForm.$valid" value="Save my informations" class="btn btn-success" />
</form>
<pre>user = {{pageCtrl.user | json}}</pre>
<pre>tmpUser = {{pageCtrl.tmpUser | json}}</pre>
</body>
Use your ng-model to bind to a temp object , like :
this.tmpUser = {
'name':'Robert',
'age':'30'
}
Your form would be:
<form name="userForm" ng-submit="userForm.$valid && pageCtrl.userForm(user)" novalidate>
<label for="name">Name *</label>
<input type="text" name="name" ng-model='pageCtrl.tmpUser.name' class="form-control" required/>
<label for="age">Age *</label>
<input type="text" name="age" ng-model='pageCtrl.tmpUser.age' class="form-control" required/>
<span ng-if='!userForm.$valid' class="error">Invalid form</span>
<input type="submit" value="Save my informations" class="btn btn-success"/>
</form>
keep your user object :
this.user = {
'name':'Robert',
'age':'30'
}
And when you submit the form, update the user object.
Let's say this is your header,
<header><span ng-show="pageCtrl.formSubmitted">{{ pageCtrl.user.name }}</span></header>
In the pageCtrl.userForm(user) function just make the pageCtrl.formSubmitted true once your form is successfully submitted. Cool things, is you can use this boolean for other purposes as well.

Data From Svc Not Modeling Into View Elements AngularJS

I have a view that is modeled to functions which pass data through to a database. This is all working and I see the data coming back when called, but it is not pre-populating the fields in my view when it comes back. I've been banging my head for a while on this. Everything is modeled (from what I can tell) properly.
I have stepped through the JS code below in Chrome and see the data being assigned to my $scope variables from the data.XXX return.
But, after load finishes, it's not preselecting my radio button or populating the fields with the data. Any help greatly appreciated.
Here is the View:
<div class="notification-container">
<form name="notificationForm" class="form-horizontal" ng-submit="saveQrNotifications()">
<div class="list-unstyled">
<input id="text" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="text" type="radio" ng-value="1001"> Text Message<br>
<input id="email" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="email" type="radio" ng-value="6"> Email<br>
<input id="voice" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="voice" type="radio" ng-value="1003"> Voice<br>
<input id="nocontact" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="nocontact" type="radio" ng-value="1000"> Do Not Contact<br>
</div>
<div class="col-md-12 notification-fields" ng-show="notifyFieldVisibility == true">
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '1001'">
<label class="notication-input">Text Number</label>
<span class="clearfix"></span>
<input class="form-control area-code" type="text" ng-model="NotificationMethods.NotificationTextAreaCode" placeholder="(555)" required>
<input class="form-control phone-number" type="text" ng-model="NotificationMethods.NotificationTextPhoneNumber" placeholder="555-5555" required>
</div>
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '6'">
<label class="notification-input" for="email">E-mail Address
<input class="form-control" id="email" name="email" type="text" ng-model="NotificationMethods.NotificationEmailAddress" placeholder="ex.me#example.com" required>
</label>
</div>
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '1003'">
<label class="notication-input">Voice Number </label>
<span class="clearfix"></span>
<input class="form-control area-code" type="text" ng-model="NotificationMethods.NotificationVoiceAreaCode" placeholder="(555)" required>
<input class="form-control phone-number" type="text" ng-model="NotificationMethods.NotificationVoicePhoneNumber" placeholder="555.5555" required>
<label class="small">Ext.</label>
<input class="form-control extension" type="text" ng-model="NotificationMethods.NotificationVoiceExtension" placeholder="555">
</div>
<span class="clearfix"></span>
<div ng-show="notifyLoading" class="text-center" style="margin-top: 10px;">
<i class="fa fa-spinner fa-spin"></i> Saving...
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary notification-btn">Save Notifications</button>
</div>
</div>
</form>
</div>
Here is my controller:
DATA COMING FROM DB:
if (data.StatusCode == "SUCCESS") {
$scope.refill = data;
//$scope.deliverTypes = data.DeliveryTypes;
$scope.showError = false;
$scope.submitRefill = true;
$scope.findRefillStatus = userMessageService.QuickRefillMessage(data.Prescriptions[0]);
$scope.isRefillable = data.Prescriptions[0].IsRefillable;
$scope.prescription.noPrescription.$valid = true;
$scope.loading = false;
$scope.NotificationMethods.NotificationEmailAddress = data.NotificationEmailAddress;
$scope.NotificationMethods.NotificationMethodId = data.NotificationMethodId;
$scope.NotificationMethods.NotificationTextAreaCode = data.NotificationTextAreaCode;
$scope.NotificationMethods.NotificationTextPhoneNumber = data.NotificationTextPhoneNumber;
$scope.NotificationMethods.NotificationVoiceAreaCode = data.NotificationVoiceAreaCode;
$scope.NotificationMethods.NotificationVoicePhoneNumber = data.NotificationVoicePhoneNumber;
$scope.NotificationMethods.NotificationVoiceExtension = data.NotificationVoiceExtension;
}
Figured it out. I was declaring the controller on the view used in ng-include. Removing that and letting the view inherit controller from surrounding view solved issue.

Https form post in javascript form with scrapy

I am using scrapy and I want to post parameters to the following https login form:
<form id="loginForm" name="loginForm" action="/ax/login/loginNN.html" onsubmit="loginWidget.logIn(); loginWidget=null;" onkeypress="checkForReturn(this, event)" method="post">
<input type="hidden" name="referer" value="/ax/web/nn/index.html" />
<input type="hidden" name="encryption" value="1" />
<div class="fakePasswordContainer">
<input class="js-clear_field" tabindex="-1" name="fake_password" type="password">
</div>
<div class="input-group input-group-custom">
<span class="input-group-addon"><span class="icon icon_user"></span></span>
<input type="text" class="form-control lowercase" placeholder="Username" id="input1" name="8d144c359a21a05e83e9a1b56ec6a8e7" type="text" autocomplete="off" >
</div>
<div class="input-group input-group-custom">
<span class="input-group-addon"><span class="icon icon_key"></span></span>
<input id="fakeholder" type="text" class="form-control" placeholder="Password" autocomplete="off" style="display:none;">
<input id="pContent" type="password" class="form-control" placeholder="Password" autocomplete="off">
<input id="pContHidden" name="420d27b4073e303b678e19767daa0f38" type="hidden" autocomplete="off" />
</div>
<div class="row multiple-button-container">
<div class="col-sm-7 align-left">
<p class="btn-inline">Password forgotten?</p>
</div>
<div class="col-sm-5">
<button id="login_btn" type="button" class="btn btn-primary btn-custom btn-block cta" onclick="if (loginWidget != null) return loginWidget.logIn()">Log in</button>
</div>
</div>
</form>
I fail to do so and this is my spider parser:
def parse(self, response):
sel = Selector(response)
login_parameters = sel.xpath("//div/div/div/div/div/div/form[#id='loginForm']/div")
user_param = ""
pass_param = ""
for parameter in login_parameters:
param1 = parameter.xpath('input[#id="input1"]/#name').extract()
if param1:
user_param = param1[0]
param2 = parameter.xpath('input[#id="pContHidden"]/#name').extract()
if param2:
pass_param = param2[0]
form_data = {u'referer':u'/ax/login/startSE.html?cmpi=start-login',u'encryption': u'1',u'fake_password':,user_param:u'123456',,pass_param : u'Abcdefg'}
url = u'https://www.ordnet.se/ax/login/loginNN.html'
print form_data
yield FormRequest(url, callback=self.parse2, formdata=form_data)
Am I missing any parameters in the post or am I doing anything else incorrectly? Any help would be greatly appreciated.
It would be better if you do it with selenium. To prevent fake requests and bots usually there are hidden elements with tokens and CSRF strings which you can't easily fake.
With selenium you can sit in the driver seat and control execution of scripts or can trigger events.

Categories