Why is this AJAX form not submitting? - javascript

Whenever I press the "Submit Request" button within the form, no error pops up and it does not redirect me to the page which is noted in the PHP script. Any ideas as to why this is occurring?
Code from webpage w/ form:
<form id="consultation-reservation" action="actions/consultation-request.php" method="post">
<input name="fullname" type="text" placeholder="Full Name (Required)" class="mt5" />
<input name="phonenumber" type="text" placeholder="Phone Number (Required)" class="mt5" />
<input name="emailaddress" type="text" placeholder="E-Mail Address (Required)" class="mt5" />
<textarea name="comments" placeholder="Additional Comments/Questions" class="mt10"></textarea>
<p class="hidden" id="consultation-reservation-error">Please verify all required fields are complete.</p>
<a class="button" id="consultation-reservation-submit">Submit Request</a>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#consultation-reservation-submit").click(function(){
$("#consultation-reservation").submit();
});
});
$('#consultation-reservation').submit(function(e) {
register();
e.preventDefault();
});
function register()
{
jQuery.ajax({
method: "POST",
url: "actions/consultation-request.php",
data: $('#consultation-reservation').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).hide(0).slideDown(500, 'linear');
else $('#'+el).hide();
}
function error(act,txt)
{
if(txt) $('#consultation-reservation-error').html(txt);
$('#consultation-reservation-error').hide(0).slideDown(500, 'linear');
}
</script>
PHP Script which is supposed to be executed via ajax: (I am going to apply the mysql_real_escape_string to the variables containing the form data, but just haven't yet)
<?php
if(empty($_POST['fullname']) || empty($_POST['phonenumber']) || empty($_POST['emailaddress']))
{
die('{status:0,"txt":"Please verify all required fields are complete."}');
}
$name = $_POST['fullname'];
$phonenumber = $_POST['phonenumber'];
$email = $_POST['emailaddress'];
$comments = $_POST['comments'];
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['emailaddress'])))
die('{status:0,"txt":"Please Provide a Valid E-Mail Address."}');
echo '{status:1,txt:"consultation-request-successful"}';
?>

echo '{status:1,txt:"consultation-request-successful"}';
The above is invalid JSON because it doesn't use the double quotes around the txt and status key. You specified the response data type as json, so jQuery will try to parse the response as JSON, and if it fails it will run the error handler (if set) instead of the success handler.
So either add the double quotes, or build the JSON in another way:
$response = array('status' => 1, 'txt' => 'consultation-request-successful');
echo json_encode($response);
Building JSON in this way is much better because all of the quotes will be automatically handled, also special characters within the values will be escaped as necessary.

Related

how to insert data information in db using html and javascript

I have created a chatbot using rivescript and javascript. I want to save the user's messages and chatbot responses to a database.
In html code I have made this form for the messages:
<div id="dialogue"></div>
<form onSubmit="return chatbot.sendMessage()">
<div class="text-box">
<input type="text" name="message" id="message" autocomplete="off" placeholder="Please wait... loading...">
<input class="send-button" type="submit" value=" " id="butsend">
</div>
</form>
</div>
I used a php file named connect.php to connect with the db.
I modified the command:
<form onSubmit = "return chatbot.sendMessage ()"> to
<form onSubmit = "return chatbot.sendMessage ()" method = "POST" "action =" connect.php>
resulting in the user's first message being entered in the database and then a new blank page appearing instead of the dialog.
Ιs there any way to continue the dialogue and at the same time store the data in the database when the send button is pressed?
I have solved the problem using this function:
function writetoDB(inputmessage, outputmessage){
$.ajax({
url: "save.php",
type: "POST",
data: {
user: inputmessage,
botreply: outputmessage,
},
cache: false,
success: function(dataResult){
}
})
}
that calls the php file:
<?php
include 'database.php';
$user=$_POST['user'];
$botreply=$_POST['botreply'];
$sql = "INSERT INTO `dialogs`( `user`, `bot`)
VALUES ('$user','$botreply')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
?>
My problem now is that not all values are imported in database. For example, if there are 20 messages, only 10 are written to the db.

Pass JavaScript argument to PHP with ajax

I need to be able to send a JavaScript variable to a PHP function. I was able to get it working for hard-coded values such as the code below.
<button onclick="submitform()">Click me</button>
<script>
function submitform(){
document.write(' <?php send_mail('hello'); ?> ');
}
</script>
<?php
function send_mail($subject){
//$subject => 'hello'
//Do something with subject
}
?>
However, I cannot replace the hard-coded value with a variable. I would also like to find another way to issue the PHP function call. I believe the solution lies in an ajax request. I cannot find a way to do this with the PHP code directly embedded as it is now. All of the other examples I cannot get to work. If possible, I would appreciate a demo as well. Thanks!
You can do it using forms:
<form action="send_mail.php" method="post">
<input type="text" id="mail" name = "mail">
<input type="submit" class="btn" value="Send Mail">
</form>
Then you can access the mail using $_POST["mail"] from the send_mail.php page
Another way to do it is ajax:
$.ajax({ url: '/send_mail.php',
data: {action: 'sendEmail', mymail:$('#mail').val()},
type: 'post',
success: function(output) {
alert(output);
}
});
Then in the send_mail.php page you can do:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
$mail = $_POST['mymail'];
switch($action) {
case 'sendEmail' : send_email();break;
// ...etc...
}
}
Demo for same page call:
<?php
if(isset($_GET['action'])=='myfunc') {
echo "Hello";
}
?>
<form action="?action=myfunc" method="post">
<input type="text" id="mail" name = "mail">
<input id="clickMe" type="submit" value="clickme"/>

Ajax call to a php file is not working

I am trying to implement a simple form which will eventually connect to a database and make entries in it. In the tag,I am calling the php file which will connect me to the database in the back-end.
index.html
<html>
<head>
<script>
function submitForm(formId){
//var formData= $.(formId).serialize();
$.ajax({
url:'new-user.php',
type:'POST',
data:{
user_name=$("#user_name").val(),
password=$("#password").val();
}
success:function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<form onsubmit="submitForm('#myForm');" id='myForm'>
User Name: <input type="text" name="user_name" id="user_name" />
Password: <input type="text" name="password" id="password" />
<input type="submit"/>
</form>
</body>
</html>
new-user.php
<?php include 'database.php';?>
<?php
mysqli_query($connect,"create table login(User_name varchar(50) NOT NULL,Password varchar(50) NOT NULL)");
$user_name=$_POST['user_name'];
$password=$_POST['password'];
if(empty($user_name)){
$name_error="name is required";
}
mysqli_query($connect,"Insert into login(User_name,Password) values('$user_name','$password')");
if(mysqli_affected_rows($connect)>0){
echo "<p>Credentials added</p>";
echo "<a href='index.html'>Go back</a>";
}else{
echo "<p>Error</p>";
echo mysqli_error($connect);
}
?>
database.php
<?php
$connect=mysqli_connect('localhost','root','','testdb');
if(mysqli_connect_errno($connect)){
echo 'failed to connect';
}
?>
The above is not creating any table in the testdb database.Neither,it is generating any alert messages.The Url however changes after clicking the submit button as http://localhost/try2/?user_name=aayushi&password=ded but after that nothing happens. This is my first php code, so I don't really know what's the meaning of this exactly.
Okay, since no one seems to actually be reading your code, there's a couple of syntax errors that I missed until I threw it into PhpStorm
Change your function to this:
function submitForm(formId){
$.ajax({
url:'/new-user.php',
type:'POST',
data:{
user_name: $("#user_name").val(),
password: $("#password").val()
}
})
.complete(function (response) {
alert(response)
})
return false; // Prevents the form from submitting the standard way
}
EDIT: Change the form to this:
<form onsubmit="return submitForm('#myForm');" id='myForm'>
In your ajax method, the success property is wrong
It is written as suceess, when it was supposed to be success
Also, to avoid refreshing the page, insert return false; at the end of the function submitForm

PHP form > JS OnUpdate > AJAX > should return MySQLi data, but I don't understand the code

I take no credit for the JS or AJAX code and I don't understand it. (Thank you Alon Alexander)
I have no AJAX knowledge and I would rather use PHP/JS with no JQuery, but I don't understand how to make it work.
I have a form that uses OnUpdate to fire a JS code that then uses AJAX to perform a SQLi query that should return the search data.
Problem is the return is alway the same even if I use data I KNOW should be returned true (file already exists), but Always returns 'New Entry' in my "Notice" Paragraph
Further, if record found I will then use JS to update form fields with record data. But that is for the next step in this. First need this to work.
i.e. "Record Exists" and form populates with that record info
or "New Entry" and forms stays blank.
index.php //reduced to needed info only
<?php include("process.php"); ?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/phone.js"></script>
<script type="text/javascript" src="js/entrynum.js"></script>
</head>
<body>
<?php
if (isset($_POST['reg-submit'])) {
echo "<p id='notice' style='padding: .5em; border: 2px solid red;'>Entry $entrynum Saved!<br>$timenow on $datenow</p>";
} else {
echo "<p id='notice' style='display: none; padding: .5em; border: 2px solid red;'></p>";
}
?>
<main>
<div class="Container">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend><h1>Registration</h1></legend>
<label for="entrynum">Entry Number</label>
<input type="number" pattern="\d*" name="entrynum" id="entrynum" value="" required="true" placeholder="" autofocus onchange="entry_check()" />
<label for="fname">First Name</label>
<input type="text" name="fname" id="fname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<label for="lname">Last Name</label>
<input type="text" name="lname" id="lname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<input type="submit" name="reg-submit" id="reg-submit" value="Submit" />
</fieldset> <!-- Registration Form-->
</form>
</div>
</main>
</body>
</html>
entrynum.js
function entry_check() {
var entrynum = $("#entrynum").val();
// Send the AJAX call
$.post(
'entrysearch.php', // TO search.php page
{entrynum: entrynum}, // the DATA sent with the request
function(data) { // a CALLBACK function
if (data == 'none') { // no rows were found or an error occurred
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
return;
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}
);
}
entrysearch.php
<?php
include("includes/connect.php");
if (!isset($_POST['entrynum'])) {
echo 'none';
die();
}
$sql = $db->prepare("SELECT * FROM HeatWaveData WHERE entrynum=%d", $_POST['entrynum']);
$results = $db->query($sql);
$result = $results[0];
if (!$result) {
echo 'none';
die();
}
echo json_encode($result);
?>
I suggest you to use $.ajax function instead of post.
You can try by adding an id to the form by adding id="myform", then change entrynum.js as it follows:
// Change onSubmit behaviour for the form
$("#myform").on("submit", function(e) {
// Prevent page reload
e.preventDefault();
$.ajax({
// Get form action or uses current page.
url : $(this).attr('action') || window.location.pathname,
type: "POST",
// Get all input to submit and serialize on array (this will become $_POST)
data: $(this).serialize(),
success: function (data) {
//Here you have server response
},
error: function (jXHR, textStatus, errorThrown) {
// If error thrown jXHR contains XMLHttpRequest stuff like status
console.log(jXHR);
// You will see on an alert the real error thrown
alert(errorThrown);
}
});
});
FINALLY! It seems the sql needed a var ($entry) instead of using $_POST['entrynum']... Not sure why.
Then if no records found the ajax would not return anything (not even NULL). So I had to add some if statements and return '0' if no records found.
Further, it helped to add datatype "json' so object was parsed.
Javascript:
function entry_check() {
var entrynum = $("#entrynum").val();
$.post(
'entrysearch.php',
{entrynum: entrynum},
function(data) {
if (!data) {
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}, "json"
);
}
entrysearch.php
<?php
if (isset($_POST['entrynum'])) {
$entry = $_POST['entrynum'];
include("connect.php");
$sql = ("SELECT * FROM HeatWaveData WHERE entrynum = $entry");
if ($results=mysqli_query($db,$sql)) {
if ($rowcount=mysqli_num_rows($results)) {
$result = $results->fetch_object();
echo json_encode($result);
} else {
echo $rowcount;
}
}
}
?>
It works! Took me all night of research reading examples and docs.

Calling ajax inside ajax html return prevents first ajax script from further working

HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
...
...
<form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input type="submit" value="submit" />
</form>
<div id="validate_mail_result"></div> // placeholder for html code that is returned
<script> // main script
var form=$('#validate_mail');
form.submit(function(ev){
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : form.serialize(),
success : function(result{
$('#validate_mail_result').html(result);
}
});
ev.preventDefault();
});
</script>
PHP (which is called by the main script)
<?php
...
...
// Connect to MySQL
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$connection = new mysqli($servername,$username,$password);
if (mysqli_connect_errno()){
printf("MyErrorMsg: %s\n", mysqli_connect_error());
exit();
}
// Perform request
$mail_name = $_POST[mail_name];
$full_mail_name = $mail_name . "#mydomain.me";
$connection->select_db("MAILSERVER");
$queryMailExists = "SELECT id FROM users WHERE mailname = '" . $mail_name . "'";
$resultMailExists = $connection->query($queryMailExists);
$row_cnt = $resultMailExists->num_rows;
$connection->close();
if (is_valid_email_address_5321($full_mail_name)==0){
echo "Not a valid email-address according to RFC5321";
}elseif(row_cnt==0){ //check if email name allready taken
echo "Mail available";
echo "
<form id=\"purchase_mail\" action=\"/wp-content/custom-php/purchase_mail.php\" method=\"POST\">
<input id=\"password\" style=\"width: 280px;\" name=\"password\" type=\"password\" value=\"\" />
<div id=pswrd_struct_chk></div>
<input id=\"password_retyped\" style=\"width: 280px;\" name=\"password_retyped\" type=\"password\" value=\"\" />
<div id=pswrd_match_chk></div>
<script> // this script and the one after this are blocking the main script
var form=$('#purchase_mail');
$('#password').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_structure_check.php\",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val(\"\");
$('#pswrd_match_chk').html(\"\");
});
</script>
<script>
var form=$('#purchase_mail');
$('#password_retyped').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_match_check.php\",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
<input type=\"submit\" value=\"PAY\" />
";
}else{
echo "<div>Mailname allready taken!</div>";
}
?>
When i comment out the two last scripts everything works as intended. The 3 different if-cases in the PHP do echo their html codes into the placeholder but when i leave the scripts uncommented once the "elseif(row_cnt==0)" section is executed the main script gets stuck and i do not get any echo for the other two if-cases no matter what is submited (enterd in the input field with the id=mail_name).
I was not able to google my problem.
Thanks for your time end effort.
AJAX does not allow script tags to be passed in the results when type is HTML. Supposing that you somehow manage to pass the scripts, you will still have to retrigger the script which is somewhat bothersome.
I would suggest you to write the html adding code in the success message and passing on the variables such as form action, URLs, etc from PHP. This way you won't face those issues and you will also be able to get the job done.
I checked your code. You can try doing something like:
First AJAX:
$.ajax({
//logic for the first ajax
}).done(function(){
//**second ajax**
})
First of all you should follow the rule:
in php script - just php code, no js and css; in js script - just js, no css.**
It not just a good style, it will help you to facilitate your work!
I just move your html and js from validate_mail.php to main page, and it looks like:
<html>
<head></head>
<body>
<form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input id="btn_validate_mail" type="button" value="submit" />
</form>
<div id="validate_mail_result1" style="display: none;">Not a valid email-address according to RFC5321</div>
<div id="validate_mail_result2" style="display: none;">
Mail available
<form id="purchase_mail" action="/wp-content/custom-php/purchase_mail.php" method="POST">
<input id="password" style="width: 280px;" name="password" type="password" value="" />
<div id="pswrd_struct_chk"></div>
<input id="password_retyped" style="width: 280px;" name="password_retyped" type="password" value="" />
<div id="pswrd_match_chk"></div>
</form>
</div>
<div id="validate_mail_result3" style="display: none;">Mailname allready taken!</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$('#btn_validate_mail').click(function () {
var form = $('#validate_mail');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (result) {
$('#validate_mail_result'+result).show();
},
error: function (xhr, status, error) {
// If you will receive any errors - you will see it here.
console.log(error);
},
complete: function () {
form.hide();
}
});
});
$('#password').keyup(function(ev){
var form=$('#purchase_mail');
$.ajax({
type : form.attr('method'),
url : "/wp-content/custom-php/password_structure_check.php",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val("");
$('#pswrd_match_chk').html("");
});
$('#password_retyped').keyup(function(ev){
var form=$('#purchase_mail');
$.ajax({
type : form.attr('method'),
url : "/wp-content/custom-php/password_match_check.php",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
</html>
It looks much better, but still terrible. And js don't should be here, and css too.
Now validate_mail.php looks:
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$connection = new mysqli($servername,$username,$password);
if (mysqli_connect_errno()){
printf("MyErrorMsg: %s\n", mysqli_connect_error());
exit();
}
// Perform request
$mail_name = $_POST['mail_name'];
$full_mail_name = $mail_name . "#mydomain.me";
$connection->select_db("MAILSERVER");
$queryMailExists = "SELECT id FROM users2 WHERE mailname = '" . $mail_name . "'";
$resultMailExists = $connection->query($queryMailExists);
$row_cnt = $resultMailExists->num_rows;
$connection->close();
if (is_valid_email_address_5321($full_mail_name)==0){
echo 1;
}elseif($row_cnt==0){ //check if email name allready taken
echo 2;
}else{
echo 3;
}
So much easier...
I don't want talk about xss, sql injections and else, because your question not about it, but you should remember about it.
You need to continue separate js and html and css...
I just try to show how it can be much easier to reach what you need... hope it will be helpful...
Good news. You just had typos in your code. I ran the relevant parts on a local server and your scripts are executing as expected. Enjoy!
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<form id="validate_mail" action="validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input type="submit" value="submit" />
</form>
<div id="validate_mail_result"></div>
<script> // main script
var form = $('#validate_mail');
form.submit(function(ev){
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : form.serialize(),
// success : function(result{ <-- typo
success : function(result){
$('#validate_mail_result').html(result);
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP - validate_mail.php
<?php
// }elseif(row_cnt==0){ <-- typos here too, maybe more above, didn't check
// }else if($row_cnt == 0){
echo "Mail available";
echo "
<form id=\"purchase_mail\" action=\"/wp-content/custom-php/purchase_mail.php\" method=\"POST\">
<input id=\"password\" style=\"width: 280px;\" name=\"password\" type=\"password\" value=\"\" />
<div id=pswrd_struct_chk></div>
<input id=\"password_retyped\" style=\"width: 280px;\" name=\"password_retyped\" type=\"password\" value=\"\" />
<div id=pswrd_match_chk></div>
<script> // this script and the one after this are blocking the main script
var form=$('#purchase_mail');
$('#password').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_structure_check.php\",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val(\"\");
$('#pswrd_match_chk').html(\"\");
});
</script>
<script>
var form=$('#purchase_mail');
$('#password_retyped').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_match_check.php\",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
<input type=\"submit\" value=\"PAY\" />
";
//}else{
// echo "<div>Mailname allready taken!</div>";
//}
?>
Ignoring the already-mentioned errors here (invalid HTML, invalid PHP, etc.), your easiest (and best) solution to this is simply to refactor your code so it doesn't return the HTML/JS. Just put all of the HTML/JS that is currently being returned by the PHP into your page and hide it. Have the PHP return a status code of some sort ("invalid-email"/"ok"/"taken", etc.) and have jQuery hide/unhide the appropriate response on the page. This keeps a separation of concerns between your presentation and your business logic.
If you are using jQuery version 1.7 and above
Change
var form=$('#validate_mail');
form.submit(function(ev){
$.ajax({
To:
var $(document).on('submit','#validate_mail',function(ev){
$.ajax({
Also try and keep your JQuery scripts together maybe in a main.js file and definitely outside and away from your PHP. So you should write the JS for the #purchase_mail directly under your #validate_mail submit function in the same way as I described and it will work when you ajax your form into the page.
The script you are pulling in with Ajax will not work unless you evaluate eval() it somehow but doing that will open your script up to potential security vulnerabilities.
Hope that helps dude

Categories