I have a simple form with one input field and one submit button. When i click submit, i get error
This is the query in php. Query:
//Using MySQLi
$stmt = $con->prepare("INSERT INTO `emailsubscribe`
(email,medium,country)VAlUE(?,?,?)"); // Use prepared statements.
$stmt-> bind_param("sss", $email, $medium, $country);
$stmt-> execute();
This table has 3 columns email, medium and country.
$('#formoid').on('submit', function() {
$.ajax({
type: "POST",
url: "subscribe.php",
data: $(this).serialize(),
success: function(data){
$('.message').html(data).fadeIn();
}
});
return false;
});
<div class="message" style="color:black;"></div>
<form action="subscribe.php" title="" method="post" id="formoid">
<input type="email" id="email" name="email" minlength="7" size="40" placeholder="Enter your email here.." required><br><br>
<input type="hidden" name="medium" value="subbox" />
<input type="hidden" name="country" value="<?php echo $country; ?>" />
<input type="submit">
</form>
First, let's wrap up the HTML data.
<div class="message"></div>
<form action="subscribe.php" name="subscribeForm">
<input type="email" name="emailsub" minlength="7" size="40" placeholder="Enter your email here.."><br><br>
<select name="medium">
<option value="">Select Medium</option>
<option value="english">English</option>
<option value="hindi">Hindi</option>
<option value="japanese">Japanese</option>
</select>
<br><br>
<select name="country">
<option value="">Select Country</option>
<option value="India">India</option>
<option value="USA">USA</option>
<option value="Japan">Japan</option>
</select><br><br>
<input type="submit" id="action">
</form>
AJAX code below takes the form details and sends to subscribe.php. Note that document.subscribeForm below takes your form field variables and stores in the form. For this only name value in HTML part is enough. Hence, I have not added any id field in the HTML form fields.
$('#action').click(function() {
var form = document.subscribeForm;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr("action"),
data: dataString,
beforeSend: function(){
$('.message').hide();
$("#action").val('Please wait...');
},
success: function(data){
$('.message').html(data).fadeIn();
}
});
return false;
});
Once the data is sent to subscribe.php, it's now time to process it.
// Storing data in variables
$email = (!empty($_POST['emailsub'])?$_POST['emailsub']:null;
$medium = (!empty($_POST['medium'])?$_POST['medium']:null;
$country = (!empty($_POST['country'])?$_POST['country']:null;
if($_POST){
// Check if email submitted is empty or not. If yes, script will stop executing further.
if($email == null){
echo "Email is required";
exit();
}
// Check if medium submitted is empty or not. If yes, script will stop executing further.
if($medium == null){
echo "Medium is required";
exit();
}
// Check if country submitted is empty or not. If yes, script will stop executing further.
if($country == null){
echo "Country is required";
exit();
}
// All checks cleared. Process the data.
//Using MySQLi
$stmt = $con->prepare("INSERT INTO emailsubscribe(email, medium, country)VAlUES(?,?,?)"); // Use prepared statements.
$stmt-> bind_param($email, $medium, $country);
$stmt-> execute();
// Using PDO (Better: A big bonus is that you can use a readable `:name` instead of confusing `?`)
$stmt = $con->prepare("INSERT INTO emailsubscribe(email, medium, country)VAlUES(:email, :medium, :country)"); // Use prepared statements.
$stmt-> bindValue(':email', $email);
$stmt-> bindValue(':medium', $medium);
$stmt-> bindValue(':country', $country);
$stmt-> execute();
// Echo Message
if($stmt){
echo "Success";
}else{
echo "Error";
}
}
This is the proper way how you should process your forms.
Firstly I don't see any medium or country in your form as inputs. So I changed your HTML code
$('#formoid').on('submit', function() {
$.ajax({
type: "POST",
url: "subscribe.php",
data: $(this).serialize(),
success: function(response) {
$(this).hide(); //sets css display:none to form
var message = "Thank you!";
$('.container-fluid').html(message);
}
});
});
<form action="subscribe.php" title="" method="post" id="formoid">
<input type="email" id="emailsub" name="email" minlength="7" size="40" placeholder="Enter your email here.." required><br><br>
<input type="text" id="" name="medium" size="40" placeholder="Enter here.." required>
<input type="text" id="" name="country" size="40" placeholder="Enter here.." required>
<input type="submit">
</form>
Then in your subscribe.php do the following. Take note, I just copied your exact SQL code. Use prepared statements or PDO to avoid SQL injection
$qry = mysqli_query($con,"INSERT into `emailsubscribe` (email,medium,country) value ('".$_POST['email']."','".$_POST['medium']."','".$_POST['country']."')");
Related
Problem: How can I update a form's select input values and text input fields based on a MySQL query after select input's onchange event is fired?
What I've tried:
I have tried to use AJAX with post and get data types, calling a php file that runs the query and echoes the results. Nothing displays. Any errors I have gotten along the way are usually small things that result in server 500 error. I have placed console.log statements in the function that runs the JQuery AJAX request. The change event was detected, the ajax success was called. I also tried using .load(), with GET and POST, no luck either. I have other features that implement AJAX, and I've tried modifying them to fit this scenario and have been unsuccessful.
I also tried to only use a select input that when changed would use AJAX request and .load function to display the other inputs which would be formatted on the php side and echoed to page with selected and values reflecting the db result.
What I want:
I would like a simple example of a form with a select input with three options, text type input, and a submit button. The form is a client backend form to send updates to the MySQL db. Each input represents a filed in the db. The idea is that when the user changes the select inputs selected value, a query is done that uses the selected value for only returning one result. Each field of that one records values in db should now be reflected in the form. First, tell me if this is the correct way to approach this problem, and if not show me how you would.
Example index.php:
<form action="editForm.php" method="POST" enctype="multipart/form-data">
<select id="contact_name" name="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" name="age" placeholder="Age" required>
<input type="text" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
When on change event for #contact_name is fired I need to update the fields with the values the db has.
How would you implement this? Thanks in advance.
Update: as requested here is my JQuery code, but I know my example doesn't use the same names.
<script type="text/javascript">
$(document).ready(function(){
$('#currency_select').on('change', function (e) {
$.ajax({
type: 'post',
url: 'getCurrentValues.php',
data: {currency: 'EUR'},
success: function () {
console.log('ajax was submitted');
}
});
});
});
</script>
Here is my understanding of how to do this:
First, detect event and pass data via ajax for the query to retrieve record. This is in the document ready function to ensure DOM is ready.
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function () {
console.log('ajax was submitted');
}
});
};
editForm.php:
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
$age = $row['age'];
}
<input type="text" name="age" value="<?php echo $age; ?>">
<?php
}
?>
your index:
<select id="contact_name" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<form action="editForm.php" id="form" method="POST" enctype="multipart/form-data">
<select name="contact_name" id="contact_form" placeholder="Select Contact" required>
<option value="John Smith">John Smith</option>
<option value="Jane Doe">Jane Doe</option>
<option value="George Washington"></option>
</select>
<input type="text" id="age" name="age" placeholder="Age" required>
<input type="text" id="race" name="race" placeholder="Select Race" required>
<select id="veteran_status" name="veteran_status" placeholder="Select Veteran Status" required>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select>
</form>
$("#contact_name").on("change", function() {
var selected = $(this).val();
$("#form").load("formdata.php?contact="+selected); //normaly you do that with an id as value
OR
$.ajax({
type:"POST",
url:"formdata.php",
data: {user: selected},
dataType: "json",
success: function(response){
if(response.status == "success") {
$("#age").val(response.age);
$("#race").val(response.race);
$("#veteran_status").val(response.status);
} else {
alert("No data found for this user!");
}
});
});
and in your formdata.php file
//make your db-query
then either make the actual input fields which will be displayed if you use load
OR make something like if you use the ajax version
if($result) {
echo json_encode(array("status" => "success",age" => $result["age"], "race" => $result["race"], "status" => $result["status"]));
} else {
echo json_encode(array("status" => "failed"));
}
also you can delete the action, method and enctype in your form, as this will be set in the ajax function ;)
I would advice you to use the userid as the value in your select field, and you will also need to either also fill the contact_name IN the form OR make an hidden input field so that you can submit the form and know whos data this is..
just echo the $age variable in your editForm.php file and in the AJAX call success function alert the response. like so-
editForm.php
include 'includes/db.php';
$name = $_POST['contact_name'];
$sql = "SELECT * FROM contacts;";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$lastValues = array();
while($row = mysqli_fetch_assoc($result)) {
echo $age = $row['age'];
}
}
?>
Ajax file
$("#contact_name).on("change", function(e){
$.ajax({
type: 'post',
url: 'editForm.php',
data: {name: this.value},
success: function (response) {
alert(response);
console.log(response);
}
});
};
I hope this question is not too broad but it is not with a specific piece of code. Basically at random times and on random queries I have failures in my code. Most of the time it seems like it is on my INSERT calls. UPDATE and DELETE still work fine, but INSERT will fail across the entire page for several hours at a time before mysteriously working again. The page is only being used and tested by myself currently.
One of the sample queries.
PHP
session_start();
$poster = $_SESSION['login_user'];
$conn = new PDO("mysql:host=localhost;dbname=spectrum",'root', '1234abcd');
$u = $_POST['user'];
$p = md5($_POST['pass']);
$e = $_POST['email'];
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$t = $_POST['type'];
$sql = "INSERT INTO users(id, user, pass, email, type, first_name, last_name, poster) VALUES ('', :user, :pass, :email, :type, :first, :last, :poster)";
$q = $conn->prepare($sql);
$q->bindParam(":user", $u);
$q->bindParam(":email", $e);
$q->bindParam(":pass", $p);
$q->bindParam(":type", $t);
$q->bindParam(":first", $fn);
$q->bindParam(":last", $ln);
$q->bindParam(":poster", $poster);
$q->execute();
echo json_encode('User has been added.');
This is done through an Ajax call.
JQuery
var request;
if (request) {
request.abort();
}
var $form = f;
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: site + "/backend/formup.inc.php",
type: "post",
dataType: 'json',
data: serializedData
});
request.done(function (data){
if(data.location){
window.location.replace(data.location);
}
else{
alert(data);
location.reload(false);
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
"The following error occured: "+
textStatus, errorThrown
);
});
request.always(function (data) {
if(!data.tvar){
$inputs.prop("disabled", false);
}
});
Here is the HTML.
<form class="hidden" method="POST">
<input type="text" name="user" placeholder="Username" required/>
<input type="email" name="email" placeholder="Email" required/>
<input type="password" name="pass" placeholder="Password" required/>
<input type="text" name="first_name" placeholder="First Name" required/>
<input type="text" name="last_name" placeholder="Last Name" required/>
<input type="radio" name="type" value="0">Owner
<input type="radio" name="type" value="1">Employee
<input type="radio" name="type" value="2">Artist
<input type="radio" name="type" value="3">Venue
<input type="radio" name="type" value="4">Fan<br />
<input type="hidden" name="fname" value="add_user" />
<input type="submit" class="button" value="Add" />
</form>
Also I apologize if some formatting may be off with my questions. First time posting and getting used to the site.
I'm trying to send data using an ajax call inside of a ('#form').submit call but all the inputs of the forms are empty when I didn't intend them to be. I thought it may of had something to do with the $(document).ready statement being in the incorrect location for things to work properly but I couldn't get it to work.
<script>
(function($){
$(document).ready( function() {
$("#success").hide();
$("#inval_email").hide();
$("#text_selection").on("change", function() {
var id = $("#text_selection option:selected").attr("value");
$("#inv_text").html($("#"+id).html());
});
$("#invitation_form").submit(function(e){
var email = $('#email').val();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var message_title = $('#message_title').val();
var article_title = $('#article_title').val();
var reference_location = $('#reference').val();
var inv_text = $('#inv_text').html();
var request;
alert(first_name);
e.preventDefault();
request = $.ajax({
type: 'POST',
url: BASE_URL+"wp-content/themes/Flatter/ajax/send_invite.php",
dataType: "text",
data: { first_name: first_name, last_name: last_name, email: email, message_title: message_title, article_title: article_title, reference_location: reference_location, inv_text: inv_text },
success: function(data){
console.log(data)
if(data=="true"){
$("#invitation").hide();
$("#success").show();
}
if(data=="false"){
$("#inval_email").show();
}
}
});
});
});
})(jQuery);
</script>
<div class="col-md-4">
<div id="success" hidden><br><br>Invitation sent successfully!</div>
<div id="invitation">
<br><br><br></br><h1>Invitation Form</h1>
<form id = "invitation_form">
First Name:<input id="first_name" type="text" name="first_name" required>
Last Name:<input id="last_name" type="text" name="last_name" required>
Email Address:<input id="email" type="text" name="email" required>
Message Title:<input id="message_title" type="text" name="message_title" required>
Article Title:<input id="article_title" type="text" name="article_title" required>
Reference Location:<input id="reference" type="text" name="reference" required>
Message:<textarea id="inv_text" style="resize: none" rows="10" placeholder="Select invitation type..." readonly required></textarea>
Invitation Type:
<select id="text_selection">
<option value="empty_field"></option>
<option value="community_inv_text">Community Invitation</option>
<option value="content_submission_inv" >Content Submission Invitation</option>
<option value="individual_inv">Individual Invitation</option>
<option value="content_submission_and_individual_inv">Content Submission and Individual Invitation</option>
<option value="contributor_content_submission_inv">Contributor Content Submission Invitation</option>
</select>
<input id="submit_inv" type="submit" value="Invite">
</form>
I would greatly appreciate some help in this matter. The point of this code is to collect information from the user and send the data to another file so it can be processed. Thanks for any help in advance.
I figured it out. There was a CSS file that was modifying elements under the same name as the ones I am using in my file (i.e. first_name, last_name, email, etc.).
I have a registration form that on submit, validates passwords and domain names that match respectively. If true, I am trying to then check that the domain name does not exist in the DB via an ajax request.
<div class="grid-6">
<p>
<label for="First Name">First Name:</label>
<input type="text" name="first_name" placeholder="James" required value="">
<label for="Last Name" name="lastname">Last Name:</label>
<input type="text" name="last_name" placeholder="Brown" required value="">
<label for="email">Email:</label>
<input type="email" name="email" placeholder="email#email.com" required value="">
<label for="Preferred Password">Preferred Password:</label>
<input id="og_password" type="password" name="password" required value="">
<label for="Confirm Password">Confirm Password</label>
<input id="confirm_password" type="password" name="password_confirm" required value="">
</p>
</div><!-- /grid-6-->
<div class="grid-6">
<p>
<label for="Domain Name">Domain Name <span class="italic red">(lowercase letters and numbers only - no spaces):</span></label>
<input id="domain_name_a" type="text" name="domain_name_a" placeholder="mystudioname" required value="">
<label for="Domain Name">Confirm Domain Name:</label>
<input id="domain_name_b" type="text" name="domain_name_b" placeholder="mystudioname" required value="">
</p>
</div>
JS
unction passwordMatch() {
var pass1 = $('#og_password').val();
var pass2 = $('#confirm_password').val();
var domain1 = $('#domain_name_a').val();
var domain2 = $('#domain_name_b').val();
var error = true;
if(pass1 != pass2){
alert("Your passwords do not match!");
return false; // cancel form submission if passwords don't match
}
if(domain1 != domain2){
alert("Your domain names do not match!");
return false;
}
//no errors check DB for domain exits
checkDomain(domain1);
}
function checkDomain(domain) {
alert(domain);//testing only
$.ajax({
type:"POST",
url: "/actions/domain.php",
data: {
domain:domain
}
success: function(result) {
if(result = false) {
alert(result);
} else {
alert(result);
}
}
});
}
Things run well through the alert(domain), which is returning the correct value. The problem is somewhere in the domain.php file, the return, or just plain incorrect use of the .ajax. Here is the php
PHP
<?php
require_once("../includes/connection.php");
$domainName = $_POST['domain'];
$sql = "SELECT domain_name
FROM user
WHERE domain_name = '{$domainName}'
";
$run = mysqli_query($mysqli, $sql);
$result = mysqli_fetch_assoc($run);
echo $result['domain_name'];
?>
Any help on where I have gone wrong on this would bea appreciated.
Thanks!
Looks like you are missing a comma between the data and success function in your ajax Request.
data: {
domain:domain
} , < -- Missing comma here
success: function(result) {
If that was a direct copy of your code - you're missing a comma in the ajax call after data: {}, <- right there.
Also, remove the if...else from the success statement, because it's not done right as well (you're testing a value by using ONE equal sign, and all that does is just declare the value you're trying to test against). Just try: success: function(result) { console.log(result); alert(result); } and see what you get.
For some odd reason jQuery does not recognise the file by a shortened url.
The solution is to type the whole url -> not only smtg/smtg.php but http://www.domain.com/smtg/smtg.php.
Also, you could try to send the data in json format by adding the following line of code into your ajax call: "dataType: 'json'," and then outputting from a php file like this: "echo json_encode("return value");"
add.php - html markup.
dbadd.php - serverside script,
addpg.js - clientside including AJAX
RSV- form validator
I'm trying to do following: First validate the form (with RSV), if all things right, Then ajax submit (That's why i'm using myOnComplete). Inform user about submission. If user pressed for the first time save button then insert into db. Else update db.
The problems are:
It inserts data into db table but doesn't inform about succes or error
I can't figure out how to insert data into db If user pressed for
the first time save button or update data.
Tried all possible ways. There is no error. Please anyone help me to fix that.
addpg.js
function myOnComplete() {
return true;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Name field required.",
"required,title,Title field required.",
"required,menu, Menu field required",
"required,parentcheck,Parentcheck required",
"if:parentcheck=1,required,parent,Parent required",
"required,content,Page content field required"
]
});
});
$("#submit_btn").click(function () {
CKEDITOR.instances.content.updateElement();
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
if (message != null) {
//do what you like with the message
}
if (err != null) {
//do what you like with the erro
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
});
dbadd.php
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "All right" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
add.php
<div id="add">
<form id="add_form" method="" action="">
<input type="text" name="name" id="name" size="40" value="" class="text-input" />
<input type="text" name="title" id="title" size="40" value="" class="text-input" />
<select name="menu" id="menu">
<option value="" selected="selected">sample</option>
<option value="1">sample 1</option>
<option value="2">sample 2</option>
<option value="0">sample 3</option>
</select>
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
<select name="parent" id="parent"></select>
<textarea id="content" style="width:100%" name="content"></textarea>
<input type="submit" name="submit" class="button" id="submit_btn" value="Save" />
</form>
</div>
<script type="text/javascript" src="../../core/includes/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/addpg.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/rsv.js"></script>
For the first problem:
Without actually running the code or seeing a live example, I can't say for sure, but it looks like you have the right idea and it's just a syntax/usage error. For example:
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
Someone please scold me if I'm wrong, but aren't "msg" and "err" found in the JSON (result) rather than in xResponse? result.msg (or result["msg"]) and result.err (or result["err"])
If so, also be aware that I -believe- you will get an 'undefined' error when trying to declare both of those variables since only one of them will be present. You might want to wrap them in try/catch blocks.