i have two HTML forms, ReCaptcha showA on one, but not the other. The code is identical fro both. What could be causing this problem?
Form-1 (ReCaptcha show display underneath Choose File.
Form-2 (Shows here)
PHP
require_once '/home/deje/public_html/writers-tryst/ReCaptcha/autoload/autoload.php';
// Register API keys at https://www.google.com/recaptcha/admin
$siteKey = '6LffIB8TAAAAACanI10YyJ-Rmw8CAKobwRDqr7Yr';
$secret = '6LffIB8TAAAAAEtF8obobrsoyn7T5BSL9Ewr2rFY';
// reCAPTCHA supported 40+ languages listed here: https://developers.google.com/recaptcha/docs/language
$lang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2) : "en";;
if (isset($_POST['g-recaptcha-response'])) {
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
echo 'err=' . $errors;
} else echo "no errors";
}
echo json_encode(array("sitekey" => "$siteKey", "lang" => "$lang"));
/*
$str1 = "'<div class='g-recaptcha' data-callback='recaptchaCallback' data-sitekey='$siteKey'></div>";
$str2 = "<script type='text/javascript' src='https://www.google.com/recaptcha/api.js?hl=$lang;</script>'";
echo $str1 . $str2;
*/
JS
$(function () {
$.ajax({
url: 'php/recaptcha.php',
type: 'post',
dataType: 'json',
cache: false
}).done(function (result, success, xhr) {
var script = "<script type='text/javascript' src='https://www.google.com/recaptcha/api.js?hl=" + result.lang + "'</script>";
var div = "<div class='g-recaptcha' data-callback='recaptchaCallback' data-sitekey= " + result.sitekey + "></div>"
$("#recaptcha-elements").append(div + script)
}).fail(function (xhr, desc, err) {
var msg = formatError("Initialize recaptcha error: ", err, xhr.responseText);
showMessage(0, msg);
console.log(msg);
});
});
ReCaptcha Callback
function recaptchaCallback() {
setTimeout(function() { $("#recaptcha-elements").css({ "display": "none" })}, 10000);
$('.btn.btn-default').removeAttr('disabled');
};
Form-1 HTML
<!DOCTYPE html>
<html>
<head>
<title>Writer's Tryst - Writers Form</title>
<link type="text/css" href="css/writers.css" rel="stylesheet" />
</head>
<body>
<div class="container center_div">
<!--<form id="form-writers" class="form-horizontal well">-->
<form action="php/writers.php" method="post" enctype="multipart/form-data" target="upload-target" onsubmit="startUpload();" >
<h1>Writers</h1>
<p>
<input id="title" name="title" class="form-control" placeholder="Title" required autofocus="true" />
</p>
<p>
<label for="work-type" class="fixed50">Type:</label>
<select id="work-type" name="work-type">
<option value="fiction">Fiction</option>
<option value="non-fiction">Non-Fiction</option>
<option value="screenplay">Screenplay</option>
<option value="play">Play</option>
</select>
</p>
<p>
<p>For an explanation of the genres shown here, see <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_genres">List of genres</a></p>
<label for="genre" class="fixed50">Genre:</label>
<select id="genre" name="genre">
</select>
</p>
<p>
<label for="subgenre" class="fixed50">Sub-Genre:</label>
<select id="subgenre" name="subgenre">`
<option value="-1">None</option>
</select><br/>
</p>
<p>
<label for="nbrPages" class="fixed50">Number of pages:</label>
<input id="nbrPages" name="nbrPages" required style="width: 48px" placeholder="Pages" /><br/>
</p>
<p>For a limied time, writers can upload their sysnopsis or query letterr for <span style="color: #f00; font-weight:bold">FREE</span>. We reserve the right to change this policy without notice.</p>
<div id="tips">The objective of a sysnopsis or query letter is to entice enablers into requesting your manuscript.
It must be concise and to the point, no more than two pages and, of course very well writtehref=n. Remember, brevity is the sole of wit.
Sample Query Letter
</div>
<div class="form-group">
<p id="file-warning">Your synopsis or query letter must be a PDF file.
<a target="_blank" href="https://www.freepdfconvert.com/" target="_blank">Free file conversion to PDF</a></p>
</div>
<div class="form-group">
<label for="file2upload">PDF to Upload</label>
<input id="file2upload" name="file2upload" type="file" required value="File to upload" />
</div>
<div id="recaptcha-elements"></div>
<div class="form-group">
<button type="submit" id="writers-submit" class="btn btn-default">Submit</button>
</div>
<input id="userid" name="userid" type="hidden" />
<iframe id="upload-target" name="upload-target" src="#" ></iframe>
</form>
<input id="filesize-limit" name="filesize-limit" type="hidden" value="2250000" /> <!--document size limited to 2,250,000-->
<script src="js/recaptcha.js"></script>
<script src="js/genres.js"></script>
<script src="js/writers.js"></script>
</div>
</body>
</html>
Related
We have created a feedback form and once a user submits the feedback, we want to run the function that submits it to Airtable and then show the Next button.
Problem: The jQuery is working, showing the button after submit, but the function in (isset($_POST['submit']) isn't saving at all.
I've read through many posts but can't find the answer. Any help would be great!
Here is our current code
public function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&comments='+comments+'&reason='+reason,
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason2</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
if (isset($_POST['submit'])){
$reason = $_POST['reason'];
$comments = $_POST['comments'];
save($reason, $comments);
}
?>
<?php
}
I assume you want to transfer the entries "reason" and "comment" to the page "requests.php". Then you don't need the second post request because you use ajax:
<?php
function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'get',
data: { 'result' : comments +'*'+reason, 'feedback' : 'true' },
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason3</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
}
The "request.php" looks like this:
<?php
if(isset($_GET['feedback']))
{
$result = $_GET['result'];
$parts = explode("*", $result);
print "reason: ".$parts[1]."<br>";
print "comments: ".$parts[0]."<br>";
}
?>
What I can see from the snippet is that:
if (isset($_POST['submit'])){
While the submit button is:
<input type="submit" value="submit" name="subbtn" >
Just fix this line:
isset($_POST['submit'] to isset($_POST['subbtn']
Hope this helps.
Hello to all users of the site, my intent was to create a dynamic form for a multiple association of multiple products to the same customer, and I had the idea to implement it with the help of jquery being able to create a dynamic form, so looking on the internet I came across an example on jsFiddle, which works perfectly. The only thing that I need would be not to have an empty input where you can write but an input that has a fixed value. For example, the word "TEST", and every time a new input is generated, the input generated always has the value = "TEST".
How can I do it?
Code (you can copy and paste in your test.html it works!):
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
<script type="text/javascript">
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function () {
var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function (e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val('').focus();
});
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function () {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
</script>
How to put into.val() <?php echo $row['impianto_id'] ;?>
I have this:
<?php
session_start();
include 'connessione.php';
$id = $_SESSION['id'];
$query_string = "SELECT * FROM impianti";
$impianti = mysqli_query($connessione, $query_string);
?>
<h4>IMPIANTO ID CAMPAGNA</h4>
<select name="impianto_id_campagna">
<?php
while ($row = mysqli_fetch_assoc($impianti)) { ?>
<option value="<?php echo $row['impianto_id']; ?>">
<?php echo $row['concessionaria']; ?>
</option>
<?php } ?>
</select>
I want to echo this in .val()
But it does not work...
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
</head>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
<script type="text/javascript">
var impianto_id = '<?php $row[' impianto_id ']; ?> ';
console.log (impianto_id);
</script>
<script type="text/javascript">
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function () {var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function (e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val(impianto_id).focus();
});
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function () {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
</script>
$('.CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE').each(function() {
var $VARIABILE_DA_INZIALIZZARE = $('.CLASSE_DEL_DIV', this);
$(".add-field", $(this)).click(function(e) {
$('.CLASSE_DA_SPECIFICARE:first-child', $VARIABILE_DA_INZIALIZZARE).clone(true).appendTo($VARIABILE_DA_INZIALIZZARE).find('input').val('TEST').focus();});// here the test
$('.CLASSE_DA_SPECIFICARE .RIMUOVI_INPUT', $VARIABILE_DA_INZIALIZZARE).click(function() {
if ($('.CLASSE_DA_SPECIFICARE', $VARIABILE_DA_INZIALIZZARE).length > 1)
$(this).parent('.CLASSE_DA_SPECIFICARE').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" action="/wohoo" method="POST">
<label>impianti</label>
<div class="CLASSE_DA_SPECIFICARE-VARIABILE_DA_INZIALIZZARE">
<div class="CLASSE_DEL_DIV">
<div class="CLASSE_DA_SPECIFICARE">
<input type="text" name="impianti[]">
<input type="text" name="impianti[]">
<button type="button" class="RIMUOVI_INPUT">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
</form>
All you had to do is just add 'test' into the .val() of the input that you created.
I built a form for my class (private access only) where every one submit a form with some information. The information like Full name of the course, Subject, Select options for the list of teachers and a checkboxes for available class rooms. Some might like big or small rooms and available accessories for study. I did an effort for designing and built a form in bootstrap and php. Forms looks Okay and the validation is inline till I need to include one more feature in it. Every time when i submit a form it gets loaded. I mean, the form works with the php and html validation but the whole page gets loaded everytime i click the submit. I google it and know the this goal should be achieve by Ajax. I watched youtube videos and follow other questions here but got nothing. Inline validation or show the success message on the same page still not working. I want is when the user submit the form it will show the alert-success message on the samepage without refreshing or the error message inline if any errors there with server side validation. Codes easily available on internet.
html:
<?php
include('ajaxreturn.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<body>
<form id="submit" onsubmit="submitForm(); return false;">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="Name">Name</label>
<input class="form-control" id="name" type="text" name="name" value= "<?php if (isset($_POST["name"])) echo htmlspecialchars($_POST["name"]) ?>">
<span class="text-danger"><?php echo $name_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="form-control-label" for="subject">Subject</label>
<input class="form-control form-control" type="text" name="subject" id="subject" value= "<?php if (isset($_POST["subject"])) echo htmlspecialchars($_POST["subject"]) ?>">
<span class="text-danger"><?php echo $subject_error;?></span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="Category">Category</label>
<select class="form-control pt-0 pb-0" id="category">
<option>...</option>
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-1
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classroom_error;?></span>
</div>
div class="row">
<div class="form-check pl-3 pt-1">
<label class="form-check-label">
<input name="classroom" id="classroom" class="form-check-input" type="checkbox" <?php if (isset($classroom) && $classroom=="classroom") echo "checked";?> value="classroom">
L-2
</label>
</div>
<span class="text-danger pl-3 pt-0"><?php echo $classrooms_error;?></span>
</div>
<div class="row">
<button id="submit" name="submit" value="submit" type="submit" class="btn btn-success">submit</button>
<span class="text-danger"> Wrong!</span>
<span class="text-success"> Thanks!</span>
</div>
</form>
<!-- Optional JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<!-- <script src="main.js"></script> -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
php:
<?php
// Form Variables
$name = "";
$subject = "";
$category = "";
$classroom="";
//Error Variables
$name_error ="";
$subject_error = "";
$category_error = "";
$classroom_error = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Your Name";
} else {
$name = validation($_POST["name"]);
// Function calling and checking the letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Your name must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["subject"])) {
$subject_error = "Your Subject";
} else {
$website = validation($_POST["subject"]);
// Function calling and checking the letters and whitespace
if ((!preg_match("/^[a-zA-Z ]*$]/", $subject)) {
$subject_error = "Subjets must contain Letters, Numbers and Spaces";
}
}
if (empty($_POST["category"])) {
$category_error = "Please select categoy";
} else {
$category = validation($_POST["category"]);
}
if (empty($_POST["classroom"])) {
$classroom_error = "Select the Class Room";
} else {
$classroom = validation($_POST["classroom"]);
}
}
function validation($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Ajax:
<script>
function _(id){ return document.getElementById(id); }
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "name", _("name").value );
formdata.append( "subject", _("subject").value );
formdata.append( "category", _("category").value );
formdata.append( "classroom", _("classroom").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "ajaxreturn.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("submit").innerHTML = '<h2>Thanks '+_("name").value+', your message has been sent.</h2>';
} else {
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
Error:
ajaxform.php?name=&website=&submit=submit:78 Uncaught TypeError: Cannot read property 'value' of null
at submitForm (ajaxform.php?name=&website=&submit=submit:78)
at HTMLButtonElement.onclick (ajaxform.php?name=&website=&submit=submit:58)
submitForm # ajaxform.php?name=&website=&submit=submit:78
onclick # ajaxform.php?name=&website=&submit=submit:58
ajaxform.php?name=&website=&submit=submit:78
formdata.append( "category", _("category").value );
onclick # ajaxform.php?name=&website=&submit=submit:58
<button name="submit" id="submit" onclick="submitForm()" value="submit" type="submit" class="btn btn-success">submit</button>
Category with Select options Tag
<option value=1>1</option>
<option value=1>1</option>
<option value=1>1</option><option value=1>1</option>
Trying changing the ajax inside to this.
if (this.status == 200 && this.readyState == 4) {
this.responseText;
The rest of your code above looks right. I have never seen xmlhttprequest used having a variable name inside, Usually it looks like
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "ajaxreturn.php", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
console.log(this.responseText);
dostuff = this.responseText;
};//end onreadystate
xhr1.send();
I dont know enough php to take a look at your server side validation. I use NodeJs for all of that. Did you console log your this.responseText to see what variable your server is sending back. Also don't have your submit button submit, that is also your problem, have it run the onSubmit function. So...
<button id="submit" name="submit" onclick="submitForm()" class="btn btn-success">submit</button>
and take the onSubmit off of your form tag. I believe this will fix your issues.
When you submit the form, thats what opens a new page, when you just run the function with ajax, that won't make the browser open a new page. It just happens in the background.
Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs.
Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.
I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.
The current file is:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
?>
<script type="text/javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "demo_ajax.php",
data:'country_id='+val,
success: function(data){
$("#region").html(data);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
var size=$("#size").val();
var industry=$("#industry").val();
var country=$("#country").val();
var region=$("#region").val();
var url=$("#website").val();
var fb=$("#fb").val();
var lkdn=$("#lkdn").val();
$.ajax({
type:"post",
url:"process2.php",
data:"size="+size+"&industry="+industry+"&country="+country+"®ion="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
success:function(data){
$("#theform").hide();
$("#info").html(data);
//$("#partone").css();
$("#partone").show();
alert("Hello");
}
});
});
});
</script>
<?php include 'js/js.html'; ?>
<?php include 'css/css.html'; ?>
</head>
<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>
<div class="w3-content w3-white r_siu r_centered_div">
<header class="w3-camo-black w3-container">
<div class="w3-container ">
<span class="w3-xlarge r_caption">eRecruiter</span> <span class="large">Corporate Login</span>
</div>
<div class="w3-black">
<a href="javascript:void(0)" onclick="selectForm('register');">
<div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
</a>
</div>
</header>
<!-- Register -->
<div id="register" role="form" class="r_form_elements">
<form name="formone" class="form" autocomplete="off">
<div id="profed" class="w3-container w3-padding-16">
<div class="alert alert-error"></div>
<label>Company Industry</label>
<input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >
<label>Company Size</label>
<input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >
<label >Country:</label>
<select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
<option value="">Select Country</option>
<?php
$sql1="SELECT * FROM pentagonal_country";
$results=$mysqli->query($sql1);
while($rs=$results->fetch_assoc()) {
?>
<option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
<?php
}
?>
</select>
<label>State:</label>
<select id="region" name="region" onKeyup="checkform()">
<option value="">Select State</option>
</select>
<label>Website</label>
<input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >
<label>Facebook</label>
<input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >
<label>Linkedin</label>
<input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">
</div>
<div class="w3-row">
<button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
<button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>
</div>
</form>
</div>
<!-- Register -->
<div id="partone" style="display:none">
<form>
name : <input type="text" name="name" id="name">
</br>
message : <input type="text" name="message" id="message">
</br>
</br>
name : <input type="text" name="url" id="url">
</br>
message : <input type="text" name="fb" id="fb">
</br>
name : <input type="text" name="lkdn" id="lkdn">
</br>
</br> </br>
Send;
</form>
</div>
</div>
</body>
</html>
and the PHP-file to insert data is:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "remotejobs";
session_start();
// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
$_SESSION['message'] = "You must log in before viewing your profile page!";
header("location: error.php");
}
else {
// Makes it easier to read
$id = $_SESSION['id'];
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$active = $_SESSION['active'];
$hash = $_SESSION['hash'];
}
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$industry=$_POST["industry"];
$size=$_POST["size"];
$country=$_POST["country"];
$region=$_POST["region"];
$website=$_POST["url"];
$fb=$_POST["fb"];
$lkdn=$_POST["lkdn"];
$usrid=$id;
$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.
Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?
The most obvious bug (aside from the SQL injection stuff mentioned above) is that
<button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.
$("#submit").click(function(event){
event.preventDefault(); //prevent default postback behaviour
var size=$("#size").val();
//...etc
You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..
You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().
I have created one page with ajax function to insert data into the database so on click of submit the data is getting insert in the database but I want to show a message that data is inserted or not for that created div and showing result in that but I cant see the text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<form class="postForm" id="postForm" method="post" action="addPost.php">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url" required>
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<p>
<label for="urlType">Select Url Type :(required)</label>
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<option value="0">Server Image</option>
<option value="1">Server Video</option>
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
<p>
<label for="postType"> Select Post Type :(required)</label>
<select name="postType" id="postType">
<option value="">Select Post Type...</option>
<option value="0">Normal</option>
<option value="1">Featured</option>
<option value="2">Sponsored</option>
</select>
</p>
<p>
<label for="category"> Select Category :(required)</label>
<select name="category" id="category">
<option value="0">Select Category...</option>
</select>
</p>
<p>
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
<!-- Cancel
Add User-->
<input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">
</p>
</fieldset>
<div class="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
getCategories();
});
function getCategories() {
$.ajax({
type: "POST",
url: 'getCategories.php',
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#category').html(result);
}
});
}
function userAction(type,id){
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
if (type == 'add') {
$('#action_type_id').val(type);
$('#p_id').val(id);
}
$.ajax({
type: 'POST',
url: 'addPost.php',
data: $('#postForm').serialize(),
success:function(report){
$(".result").html(data);
location.reload();
}
});
}
</script>
</form>
</body>
</html>
addPost.php
<?php
include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {
if($_POST['action_type'] == 'add') {
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbConnection->prepare("insert into keywords(keyword)
values(?)");
$stmt->execute(array($_POST['keywords']));
//insert data into posts table
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type)
values(?,?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));
$count = $stmt->rowCount();
if ($count > 0) {
//if inserted
// echo '<p id="report">Post Submitted</p>';
echo "Post submitted.";
} else {
//if not inserted
// echo '<p id="report">Post Submitted</p>';
echo "Could not submit post.";
}
}
}
?>
Please help.. Thank you.
Here is an updated segment of your code. Form reset code has been added.
$.ajax({
type: 'POST',
url: 'addPost.php',
data: $('#postForm').serialize(),
success:function(report){
// replace data to report
$(".result").html(report);
//reset form
$(':input','#form')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
});
Please formulate a contract between the serverside and clientside
For eg:
Whenever the client is sending a request to the server
The server processes the request, builds a response for-eg( {result : "success"} or something on those lines and sends it back to the client
The client will be able to access this in the success of the $.ajax
The client will now according to the contract understand when it is success and when it is failure and perform next operations
Hope this helps.