Why is this code showing anomalous behaviour? (form not submitted) - javascript

I'm trying to submit a form using PHP and Ajax. But the problem is that sometimes it inserts one value, sometimes 2, sometimes all, and now it is inserting nothing. Why is it happening? How can I correct it?
Here's my code:
Ajax
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "submitform.php",
type: "POST",
data: $("form").serialize(),
success: function(data){
alert("well");
},
error: function(){
alert("Error");
}
});
});
});
HTML
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="text" name="name" placeholder="Enter your name" required /></td>
<td rowspan="3"><div class="propic"><img id="imgid" src="images/dp.png" /></div>
<input id="imgInput" type="file" name="image"/></td>
</tr>
<tr>
<td><input type="text" name="username" placeholder="Enter username" required /></td>
</tr>
<tr>
<td><input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required /></td>
</tr>
<tr>
<td><input type="password" name="password" maxlength="12" placeholder="Enter password" required /></td>
<td><input id="button" type="submit" name="submit" value="Sign Up" /></td>
</tr>
</table>
</form>
PHP
<?php
$conn=mysqli_connect("localhost", "root", "", "winkcage");
//$im=$_SESSION["pathsession"];
$nam=""; $usernam=""; $phon=""; $pass="";
$nam=$_POST["name"];
$usernam=$_POST["username"];
$phon=$_POST["phone"];
$pass=$_POST["password"];
$signquery="INSERT INTO signup(name, username, phone, password) VALUES('$nam', '$usernam', '$phon', '$pass')";
$signqueryrun=mysqli_query($conn, $signquery);
?>
NOTE: I don't want to insert image value right now. I'll insert it later when this problem is fixed.

You may have entered a ' quote and it killed your sql statement. This is called sql injection. To prevent sql injection you can use pdo prepared statements. You will also want to hash passwords to prevent people from stealling them if they get access to your database. Hashing password is a one way encryption that is easy to check.
$pdo = new PDO("mysql:host=$db_host;dbname=$DB_name", $user, $pass);
$sql = "INSERT INTO signup(name, username, phone, password) VALUES(':name', ':username', ':phone', ':pass')";
if ($con = $pdo->prepare($sql)) {
$con->execute([
':name' => $_POST["name"],
':username' => $_POST["username"],
':phone' => $_POST["username"],
':pass' => $_POST["password"]
]);
}
As far as the html and javascript goes. Catch the submitted form with jquerys .submit() function.
$('form').submit(function(e){
e.preventDefault();
$.post('submit.php',$(this).serialize(),function(response){
alert('complete');
}).error(function(){
alert('wrong');
});
});
This makes sure than any submit event triggers the ajax.

Since you are using a form with a submit button, when you click the button it will submit the form. You may be having a conflict between the AJAX action and the form submit. Try preventing the default action on the button click and see if it works as follows:
$(document).ready(function(){
$("#button").click(function(event){
if($("form").get()[0].checkValidity()){
$.ajax({
url: "submitform.php",
type: "POST",
data: $("form").serialize(),
success: function(data){
alert("well");
},
error: function(){
alert("Error");
}
});
});
}
event.preventDefault();
});

You assign your onclick to a button element, but there is no button element on your page, your button is an input element. Change that to a button and it may work. I personally would advise using ids, rather than element types, I think it makes things clearer, and will allow you to have more than one element of the same type without breaking your code.
Change
$("button").click(function(){
to
$("#button").click(function(){
and
data: $("form").serialize(),
to
data: $("#signupform").serialize(),

Related

Submitting AJAX form when a field is changed

I have a GET form that when submitted uses an AJAX request to update a php page.
I want this form to automatically submit any time a field is changed, the form contains mostly text inputs and a few dropdowns.
What I have tried:
onchange="this.form.submit()" - This works, but instead of AJAXing the data to the php page, it actually redirects me to the page, which is a no go.
<input type="submit"> - I would like this to be a last resort, because I want the form to send automatically, but it does work otherwise.
I know that sending a form every input change isn't usually a good idea, so ideally I would like it to send the form 1-2 seconds after inactivity (After inputting something obviously) - if that isn't possible, then every time a field is changed would be acceptable as its a low traffic server.
So my question is, what is the proper way to send a form via ajax automatically?
My current :
<form method="GET" id="submitRequest" action="showTable.php">
<th><input type="text" id="SSeries" name="SSeries" class="form-control"></th>
<th><input type="text" id="SModel" name="SModel" class="form-control"></th>
<th><input type="text" id="SSerial" name="SSerial" class="form-control"></th>
<th><input type="text" id="SColor" name="SColor" class="form-control"></th>
<th><input type="text" id="SStorage" name="SStorage" class="form-control"></th>
<th><input type="text" id="SCarrier" name="SCarrier" class="form-control"></th>
<th><input type="text" id="SType" name="SType" class="form-control"></th>
<th><input type="text" id="SUPC" name="SUPC" class="form-control"></th>
<th><input type="text" id="SStatus" name="SStatus" class="form-control"></th>
<input type="submit" class="btn btn-success">
</form>
My current AJAX:
$(document).ready(function() {
$('#submitRequest').submit( function( event ) {
$.ajax({ // create an AJAX call...
data: $('#submitRequest').serialize(), // serialize the form
type: $('#submitRequest').attr('method'), // GET or POST from the form
url: $('#submitRequest').attr('action'), // the file to call from the form
success: function(response) { // on success..
showTable();
}
});
event.preventDefault();
});
});
try this:
When input value change then form will submit,
jQuery("#submitRequest input").change(function(){
$('#submitRequest').submit();
});
I was able to fix my problem by simply changing my jquery selection and function.
I changed it from
$('#submitRequest').submit( function( event ) {
To
$('.submitForm').on('keyup', function(){
and I added submitForm to each inputs class.
You can make a post in ajax after change, and get a response from server
$("#submitRequest input").change(function(){
var data = {
SSeries : $("#SSeries").val(),
...
}
$.ajax({
url: 'your_url_method',
type: 'POST',
data: data,
success : function(res){
showTable();
console.log("Success, you submit your form" + res);
},
error : function(error){
console.log(error, "Error in submit")
}
});
});

How do I submit form using ajax

I have my form and my ajax laid out but I am not sure how to submit the form using the ajax. I've tried $('#testform').submit() but it didn't call my ajax when I wrapped it with the submit. I might of been doing it wrong. How do I get my form to submit through the ajax and not submit regularly?
<form id="testform" action="https://example.com/api/payments/" method="post">
Name<input type="text" name="name" id="name">
Card Number <input type="text" name="card_number" id="card_number" maxlength="16">
Exp Month <input type="text" name="exp_month" id="exp_month">
Exp Year <input type="text" name="exp_year" id="exp_year">
CVC <input type="text" name="cvc" id="cvc" maxlength="3">
Amount <input type="text" name="amount" id="amount">
<input type="submit" id="submit">
frm = $('#testform');
frm.submit(function(ev)
{
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "html",
//Set the HTTP headers for authentication
beforeSend: function (xhr) {
xhr.setRequestHeader('api_key', 'tiyndhinzrkzti5ody0');
xhr.setRequestHeader('email', 'example#example.com');
},
//Serialize the data sent from the form inputs
data: frm.serialize(),
success: function(data) {
$('#return').append(data);
}
});
ev.preventDefault();
});
Instead of frm.submit(function(ev) try the following code
$("#testform").on('submit', function(ev) {
ev.preventDefault();
...
});
After clicking on the submit button you should see the ajax being posted in the console. The "magic" is to attach a handler to the submit event instead of invoking the event itself. Additionally, you had a typo in your previous code ($('testform') instead of $("#testform"))

(button || input) type=submit - missing value in $_POST variable in jQuery AJAX

I have login form where are two buttons - "login" and "forgot password?" And I need to check what button user clicked.
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
</form>
var_dump($_POST) says:
array(2) { ["email"]=> string(0) "" ["password"]=> string(0) "" }
I am trying both ways (input type=submit and button type=submit) but none of them send the "submit" value.
(I am using jquery ajax)
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php", /* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function(data){
$("#login-error").html(data);
},
error:function(){
$("#result").html('There is error while submit');
}
});
});
Please do you know where the problem can be? I know, there are lot of threads about value of button but nothing works for me. I also tried this example:
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_value2
The .serializeArray() or .serialize() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.
Refer..
http://api.jquery.com/serialize
http://api.jquery.com/serializeArray
jQuery serializeArray doesn't include the submit button that was clicked
This is one way to do it, concatening data string with specific clicked button name attribute:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit">Login</button>
<button type="button" name="forgot" class="submit">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize() + '&' + this.name;
console.log(values);
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php",
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
But better would be to target specific server side script depending which button is clicked, e.g:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit" data-url="login.php">Login</button>
<button type="button" name="forgot" class="submit" data-url="forgot.php">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: $(this).data('url'),
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
It will be a lot easier to check if you name the submit input and the button differently.
You currently have this set up like this:
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
Try changing the name of the button to something like:
name="forgot"
then you can run a check on it such as
if (isset($_POST['submit'])){
stuff here
}
and a separate check for
if (isset($_POST['forgot'])){
stuff here
}
If there is not event in function then it will not prevent the submit function and by default get will be called and and $_POST will be empty for sure
Change
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
To
$("#loginForm").click(function(event){
/* Stop form from submitting normally */
event.preventDefault();
Make one more change
data: values,
To
data:$("#loginForm").serialize(),
Remove one submit type there should be only one submit type make it type of button and call onbutton click functiuon to submit via ajax it will work same as submit.

jquery .ajax() issue

I am using Jquery 1.7.1 and am having issues.. I'm working with a CRM in my script and am working to get the page finished but I'm stuck with this issue..
my html:
<form class="collector" action="https://www.domain.biz/admin/transact.php" method="POST">
<input type="hidden" name="method" value="NewProspect">
<input type="hidden" name="campaignId" value="3">
<input type="hidden" name="ipAddress" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>">
<fieldset>
<div style=" padding-left: 50px">
<table>
<tr>
<td><span style="color:red;">*</span>Your First Name:
<span id="rfvFirstName" style="display:none;">*</span>
</td>
<td><span style="color:red;">*</span>Your Last Name:
<span id="rfvFirstName" style="display:none;">*</span>
</td>
<td><span style="color:red;">*</span>Your Phone Number: </td>
<td><span style="color:red;">*</span>Primary Email: </td>
</tr>
<tr>
<td>
<input name="firstName" type="text" id="firstName" style="width:150px;" value="">
</td>
<td>
<input name="lastName" type="text" id="lastName" style="width:150px;" value="">
</td>
<td>
<input name="phone" type="text" id="phone" class="" style="width:150px;" value="">
</td>
<td>
<input name="email" type="text" id="email" class="required email" style="width:150px;" value="">
</td>
</tr>
</table>
</div>
<div class="clear"></div>
<center>
<input type="submit" name="continue" id="imgbtnSubmit" class="button" style="background-image: url('<?php echo base_url();?>inc/img/button-check.png');
background-repeat: no-repeat; width: 348px; height: 46px; border:none; background-color:transparent;" value="" />
</center>
</fieldset>
<p align="center" style="font-size:12px;">
</p>
</form>
the JS:
$('.collector').submit(function(){
validate = true;
$(this).find("input:text:visible:enabled").each(function() {
if ($(this).attr("value") == "") {
alert("Please fill in all fields!");
$(this).focus();
validate = false;
return false;
}
else if ($(this).hasClass("email") && !$(this).attr("value").match(/#/)) {
alert("Please enter an email address...");
$(this).focus();
validate = false;
return false;
}
});
if (validate != false) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $(this).serialize(),
success: function(response) {
alert(response);
}
});
}
return false;
});
Now both of these things work, and they work together fine... the issue comes in that I don't get any response and I'm not sure why. I imagine it is because of what firebug is saying... POST https://www.domain.biz/admin/transact.php 200 OK 1.04s jquery.js (line 8102)
This line in my firebug is displayed as red, and the line 8102 in jquery.js is: xhr.send( ( s.hasContent && s.data ) || null );
Here are some suggestions that might help you find the error:
In your ajax call, after the success, add the following code:
success: function(response) {
alert(response);
},
error: function(response) {
console.log(response.status + " " + response.statusText);
}
That will print in your console a clue to what is causing this error.
By the way, there are some other suggestions, your validations can be achieved with the new HTML5 input types (email, phone), if you have to maintain compatibility with browsers that don't support these, you can find a jQuery plugin that handles this.
Do you make an cross domain ajax request ? I downloaded your code and make a simple test:
Code in
localhost:8080/domain1/a.php
Make a ajax request to
localhost:8080/domain2/b.php
Error happens
Code in
localhost:8080/domain1/a.php
Make a ajax request to the page itself
(localhost:8080/domain1/a.php)
No error happens and get the expected response.
Then I googled the answer for [jquery.ajax cross domain request],and find some links may helps:
jQuery AJAX cross domain
Soluation is : dataType: 'JSONP'
$.ajax({
url:"testserver.php",
dataType: 'JSONP', // Notice! JSONP <-- P
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
},
});
I'm not sure about using $(this).serialize(). Have you tried using $('.collector').serialize() (or whichever the form is) since inside the ajax request the context may change. It's just a quick guess, hope it helps.
The same thing happened to me.And I used the same version of JQuery (1.7.1)
And the weirdest thing is that after adding "asyn:false ",it worked out.
I guess this might be a bug of JQuery.

Make a Post request with request body from HTML form

I am working on a html page which is supposed to submit a post request with request body to my server like below
<html>
<head>Customer app</head>
<body>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#customerId").serializeJSON());
console.log(MyForm);
$.ajax({
url : "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data : MyForm,
});
e.preventDefault(); //STOP default action
});
});
</script>
</html>
It does not work as expected throwing 404 Not Found getting redirected to http://localhost:7777/customerapp.html. But form data corresponding to the request submission seems to be correct.
Can someone help me fix the issue with my html code submit POST request redirection ?
Your issue is in this line:
$("#submitform").click(function(e)
Your form does not have an id but a name, so you can write:
$('[name="submitform"]').click(function(e)
That is the reason because your form is giving you a redirection error.
$('[name="submitform"]').click(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data: {"customerId": $("#customerId").val()},
success: function (result) {
//do somthing here
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td></tr>
</table>
</div>
You are already created form using html, you can add action attrbiute with value for post url like
<form name="submitform" method="post" action="/ola-drive/customer/ride">
Unless you want to use ajax, you create your data form manually
you have this:
$("#submitform").click(function(e){...}
The first problem is you are selecting an input tag, instead the Form. The second is rather the action desired, in this case should be "submit". And if you already are using JQuery you might be interested in save some space using the method 'serialize()'. Try:
$('form').on('sumbit', function(e){
e.preventDefault();
$.ajax({
url: // your path
type: 'post',
data: $(this).seialize(),
...})
})
And use an id for Form, it's easier to select it.

Categories

Resources