Showing a Bootstrap modal after form is submitted - javascript

I want to display a "thank you" modal when the page is reloaded after successful form submission.
Here's my PHP at the bottom of the <head>:
<?php
if (isset($_POST["email"]) && !empty($_POST["email"]))
{
$response_text = "Thanks, we'll be in touch soon!";
include('connect.php');
mysqli_query($con, "INSERT INTO sh_betalist (email, ip_address, signup_loc) VALUES ('" . $_POST['email'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" . "homepage')");
?>
<script type="text/javascript"> $('#thankyouModal').modal('show'); </script>
<?php
}
?>
That all works fine except for showing the modal, which doesn't happen. I don't get any errors in the JS console.
Here's my modal at the bottom of the <body>:
<div class="modal fade" id="thankyouModal" tabindex="-1" role="dialog" aria-labelledby="thankyouLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Thank you for pre-registering!</h4>
</div>
<div class="modal-body">
<p>You'll be the first to know when Shopaholic launches.</p>
<p>In the meantime, any feedback would be much appreciated.</p>
</div>
</div>
</div>
</div>

Try wrapping a $(document).ready around the javascript.
<?php
if (isset($_POST["email"]) && !empty($_POST["email"]))
{
$response_text = "Thanks, we'll be in touch soon!";
include('connect.php');
mysqli_query($con, "INSERT INTO sh_betalist
(email, ip_address, signup_loc) VALUES ('" . $_POST['email'] . "', '" .
$_SERVER['REMOTE_ADDR'] . "', '" . "homepage')");
?>
<script type="text/javascript">
$(document).ready(function(){
$('#thankyouModal').modal('show');
});
</script>
<?php
}
?>

Related

Bootstrap Model Window Not Showing by Calling Through JQuery

What I am trying to do is that pop up a bootstrap js model by using jquery call that is
$("#id").modal("show")
but it's not working in any case, there are several cases mentioned in this link but none is working in my case.
also I have gone through the following links
bootstrap model is not working
Bootstrap modal window not showing
calling to bootstrap model for a link
Bootstrap modal - popup window not showing
https://getbootstrap.com/docs/4.0/components/modal/
but I am not able to get any help, I can trigger the model by having an extra button and calling click() function of button by jquery, this works fine but not modal case.
My Modal code is here
<div class="modal fade" id="addLocationTagModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabelLocation">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" id="idButtonCloseLocation" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabelLocation">Enter Location</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-9 col-md-9 col-sm-12 col-xs-12">
<div class="form-group">
<?php
$preferredLocation = "";
if (strtolower(getUserPreferredLocation($row_user, $conn)) !== "no") {
$preferredLocation = getUserPreferredLocation($row_user, $conn);
}
?>
<input type="text" class="form-control" value="<?php echo $preferredLocation; ?>" placeholder="Location" id ="locationSuggested" name="locationSuggested" />
<span>
<span id="suggesstionBoxLocation" ></span>
</span>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<div class="pLace-order">
<button type="button" name="buttonLocation" onclick="getTagSelected();" class="btn btn-success" value="submit">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
Jquery call is here
<script>
function detachStore(url){
//alert(url);
//document.getElementById("buttonDeleteStore").click(); // Click on the checkbox
// For Testing Purpose to set the data-target
jQuery.noConflict();
$(document).ready(function () {
$("#addLocationTagModel").modal("toggle");
alert("Hello");
//$("#buttonDeleteStore").click();
// $('#addLocationTagModel').appendTo("body").modal('show');
});
}
And HTML and mixed PHP code is here below, I have onclick function on the element call that is working perfectly.
<td>
<?php
$i = 1;
foreach (unserialize($row['store_id']) as $store_id) {
$stores = $conn->query("select * from tb_stores where ID = " . $store_id);
while ($stores_row = $stores->fetch_assoc()) {
$store_price = $conn->query("select * from tb_add_price_of_products where product_id=" . $row["ID"] . " and store_id=" . $stores_row["ID"]);
$store_price_row = $store_price->fetch_assoc();
//echo $store_price_row["price"];
if ($i == 1) {
echo "<a href='#' data-toggle='modal' title='$"
. $store_price_row["price"] . "-" . $stores_row["location"] . "'"
. " onclick=\"detachStore('" . $url . "product-registry?action=delete-store&product_id=". $row["ID"] . "&store_id=" . $stores_row["ID"] . "');\" >"
. $stores_row['name'] . "</a>";
} else {
echo ", <a href='#' data-toggle='modal' title='$"
. $store_price_row["price"] . "-" . $stores_row["location"] . "'"
. " onclick=\"detachStore('" . $url . "product-registry?action=delete-store&product_id=". $row["ID"] . "&store_id=" . $stores_row["ID"] . "');\" >"
. $stores_row['name'] . "</a>";
}
$i++;
}
}
?>
<button type="button" id="buttonDeleteStore" data-toggle="modal" data-target="#add_price_modal">Button</button>
</td>
I have spent hours on it, even no JavaScript error, May be I am doing something wrong at some place, if anybody can pull it out that would be appreciated.
I was going through some other post
TypeError: $(...).modal is not a function with bootstrap Modal
and I replaced
$("#id").modal("show")
with
jQuery("#id").modal("show")
and this trick worked here and it started working. Still I don't know the reason like why it wasn't working with $.
One more thing, we need to include the jQuery.noConflict(); above then the statement to avoid repetitions.

Display search bar query results in modal

I have a search bar for users to enter a query. Upon clicking 'Search', a modal should appear with the query results.
My output from index.php is still not showing in the modal. When I click 'Search', the modal pops up with an empty body. How do I get my output from index.php to show in the modal's body?
Is there something wrong with my script? Do I need to add something to modal-body?
index.php
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form method="POST" action="#">
<input type="text" name="q" placeholder="Enter query"/>
<input type="button" name="search" value="Search" data-toggle="modal" data-target="#mymodal">
</form>
</body>
<script>
$.ajax({ type: "GET",
url: 'search.php',
success: function(data){ debugger $('#mymodal').modal('show');
$('#mymodal:visible .modal-content .modal-body').html(e); } });
</script>
<!-- The Modal -->
<div class="modal" id="mymodal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
search.php
<?php
include_once('db.php'); //Connect to database
if(isset($_REQUEST['q'])){
$q = $_REQUEST['q'];
//get required columns
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%".$q."%' OR `yupikWord` LIKE '%".$q."%') or die(mysqli_error($conn)); //check for query error
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= '<td><audio src="audio/'.$audio_name.'" controls="control">'.$audio_name.'</audio></td>';
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>
use these code of search.php
<?php
include_once('db.php'); //Connect to database
if(isset($_REQUEST['q']))
{
$q = $_REQUEST['q'];
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%".$q."%' OR `yupikWord` LIKE '%".$q."%'") or die(mysqli_error($conn));
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= '<td><audio src="audio/'.$audio_name.'" controls="control">'.$audio_name.'</audio></td>';
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>

Modal window closes on submit

I have a form in a bootstrap modal window and what is happening, is when I click the 'send' button, the modal closes and a white page displays the result of my action call to contact-form.php and shows the error message for blank field but thid should be showing in the message div in the form in the the modal window.
I am obviously doing something fundementally wrong and would appreciate any help you can offer. I wouls have done a snippet but couldn't see how to include php code.
Many thanks
Bootstrap V3.3.7
UPDATE: The form works fine if i use as normal form outside of the modal
window.
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal__title"><div style="color: white; margin-top: -14px; margin-left: 36px;">Contact Us</div></h2>
<div style="color: white; margin-left: 36px; margin-bottom: 20px;">If you need to contact us, please use this form and we shall respond as soon as possible. Thanks</div>
</div>
<div class="modal-body">
<div class="content-block contact-3">
<div class="container">
<div class="row">
<div class="col-md-9">
<div id="contact" class="form-container">
<div id="message"></div> <-ERROR SHOULD BE DISPLAYED HERE
<form method="post" action="js/contact-form.php" name="contactform" id="contactform">
<div class="form-group">
<input name="name" id="name" type="text" value="" placeholder="Name" class="form-control" />
</div>
<div class="form-group">
<input name="email" id="email" type="text" value="" placeholder="Email" class="form-control" />
</div>
<div class="form-group">
<input name="phone" id="phone" type="text" value="" placeholder="Phone" class="form-control" />
</div>
<div class="form-group">
<textarea name="comments" id="comments" class="form-control" rows="3" placeholder="Message" id="textArea"></textarea>
<div class="editContent">
<p class="small text-muted"><span class="guardsman">* All fields are required.</span> Once we receive your message we will respond as soon as possible.</p>
</div>
</div>
<div class="form-group">
<button class="btn btn-default" type="button" class="modal" data-dismiss="modal">Close</button>
<button class="btn btn-primary" type="submit" id="cf-submit" name="submit">Send</button>
</div>
</form>
</div>
<!-- /.form-container -->
</div>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
</div>
<!--// END Contact 3-1 -->
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
contact-form.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($name) == '') {
echo '<div class="error_message">Please enter your name.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Please enter a valid email address.</div>';
exit();
} else if(trim($phone) == '') {
echo '<div class="error_message">Please enter a valid phone number.</div>';
exit();
} else if(!is_numeric($phone)) {
echo '<div class="error_message">Phone number can only contain digits and no spaces.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">You have entered an invalid e-mail address, try again.</div>';
exit();
}
if(trim($comments) == '') {
echo '<div class="error_message">Please enter your message.</div>';
exit();
}
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
// Configuration option.
// Enter the email address that you want to emails to be sent to.
// Example $address = "yourname#yourdomain.com";
$address = "yourname#yourdomain.com";
// Configuration option.
// i.e. The standard subject will appear as, "You've been contacted by John Doe."
// Example, $e_subject = '$name . ' has contacted you via Your Website.';
$e_subject = 'You\'ve been contacted by ' . $name . '.';
// Configuration option.
// You can change this if you feel that you need to.
// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
$e_body = "You have been contacted by $name from your website, their message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $name by email, $email or by phone $phone";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h2>Email Sent Successfully.</h2>";
echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
?>
sendmail.js
jQuery(document).ready(function () {
$('#contactform').submit(function (e) {
e.preventDefault();
var action = $(this).attr('action');
$("#message").fadeOut(500, function () {
$('#message').hide();
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(),
},
function (data) {
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#submit').removeAttr('disabled');
if (data.match('success') != null) {
$('#contactform').fadeOut('slow');
$("#message").delay(3000).fadeOut();
$("#contactform").delay(4000).fadeIn();
$("#contactform").css("margin-top", "40px !important");
$("#contactform").trigger("reset");
}
}
);
});
return false;
});
});
I can't test you code but in my opinion i would not do the submit action with $(form).submit().... also if you are doing a event.preventDefault(), i explain better, you are doing an ajax call and with different errors you have differents answers, so in your place i would delete the action in the html at on click of the send button i would do an ajax call and manage the answer.Try in this way, because i think that if you use the submit in that way the browser interpret the submit form also because you are using the action url to send the call.
$('#cf-submit').click(function(){
name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
comments = $('#comments').val();
$.ajax({
url : 'js/contact-form.php',
type : 'POST',
data : {
name : name,
email : email,
phone : phone,
comments : comments,
},
dataType : 'html',
success : function(response){
$('#message').html(response);
}
});
});
I think you forget to put exit(); at the end of file contact-form.php

How To write correct code for Jquery Check, Validate & Redirect on success

I worked for php over last 7-8 years. But i never try ajax, jquery or javascript more then very simply copy-paste work.Now i need jquery for my work.I almost finished all worked except a login with password process. So i try to write php and jquery code for this.
Here is my code:
index.php
<html>
<head>
<script>
function login() {
// get values
var db = $("#db").val();
var pass = $("#pass").val();
// Check record
$.post("check.php", { db: db, pass: pass }, function (data) {
if (data.status=='s') //status is proper of the json object, which we gave in php code
{
var form = $('<form action="success.php" method="post">' +
'<input type="text" name="db" value="new1" />' +
'<input type="text" name="pass" value="12345" />' +
'</form>');
$('body').append(form);
form.submit();
} else {
alert( "status: " + data );
}
// close the popup
$("#pass").modal("hide");
// clear fields from the popup
$("#pass").val("");
});
}
</script>
</head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body style="color:#ece9e9;background:#184C5D;"><div style="margin-top:25%; margin-left:25%; margin-right:auto;">
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "new1";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo '<button class="btn btn-success" data-toggle="modal" data-target="#pass">Login</button><br/><br/>';
$conn->close();
?>
</div>
<!-- Modal - login -->
<div class="modal fade" id="pass" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">Enter Password</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="pass">Password</label>
<input type="text" name="pass" id="pass" placeholder="pass" class="form-control"/>
</div>
<?php echo '<input type="hidden" name="db" id="db" value="'.$dbname.'">'; ?>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="login()">Login</button>
</div>
</div>
</div>
</div>
<!-- // Modal -->
</body>
</html>
Here is code for check.php
<?php
$server = "localhost";
$username = "root";
$password = "";
$dbname = "$_POST[db]";
$pass = "$_POST[pass]";
$conn = new mysqli($server, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$dpass ="";
$sql = "SELECT pass FROM project WHERE id ='1' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dpass = $row["pass"];
}
} else {}
if ($pass == $dpass) {
echo "s";
} else {
echo "xx";
}
$conn->close();
?>
My problem is when try with correct password [12345] its showing xx in alert pop. Can anyone find out what i missing? Because i write that jquery code from 3 different source. in other hand, when i test check.php with a simple post method page, its work. means check.php is ok.
You've got 2 HTML elements with id="pass":
line 47:
<div class="modal fade" id="pass" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
and line 57:
<input type="text" name="pass" id="pass" placeholder="pass" class="form-control" />
Therefore your var pass from line 8 will take the value of the first element with id 'pass' it will encounter. In this case that will be the div from line 47.
As #jeroen van der Hel said, i've got 2 HTML elements with id="pass". So first i need to change pass to anything, like passtab
<div class="modal fade" id="passtab" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
Then main thing is response contain spaces. So i'd to trim response before doing the checking through jquery trim function.
if (data.status=='s')
to
if ($.trim(data) == 's' )
Why the response contain spaces. You can find the answers here
Space Before Ajax Response (jQuery, PHP)
2.strange thing, ajax response includes whitespace
Trailing spaces in Ajax response

Jquery ajax add to mysql database

I want to save data from input fields to mysql database so first I create a modal window and input fields:
<!-- Button trigger modal -->
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">
Add new</button>
<div id="output"></div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
......
<div class="input-group">
<span class="input-group-addon">Ime</span>
<input type="text" id="Ime" class="form-control" placeholder="Upisi ime">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Pol</span>
<input type="text" id="pol" class="form-control" placeholder="Pol (male/female)">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Godine</span>
<input type="text" id="godine" class="form-control" placeholder="Godine starosti">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Broj pojedenih krofni</span>
<input type="text" id="krofne" class="form-control" placeholder="Pojedene krofne">
</div>
</br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="newData" class="btn btn-primary">Add new data</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Now I write jQuery AJAX code to add data to database:
<script>
//add data to database using jquery ajax
$("#newData").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#ime").val()!="") {
$.ajax({
url: "add.php",
type: "POST",
async: true,
data: { Name:$("#ime").val(), Gender:$("#pol").val(), Age:$("#godine").val(), Donuts_eaten:$("#krofne").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
}
});
</script>
and finally I create a php file (add.php)
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
mysql_select_db('gmaestro_agro', $con);
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
$query .= mysql_real_escape_string($_POST['Gender']) . ", ";
$query .= mysql_real_escape_string($_POST['Age']) . ", ";
$query .= mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= ")";
$result = mysql_query($query);
if($result != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
Now, when I try to add data I just get this error: an error occurred saving your data!.
What is the problem here exactly? I try to find the error whole day...
You are not quoting your strings:
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
should be:
$query .= "'" . mysql_real_escape_string($_POST['Name']) . "', ";
(for all string values)
By the way, it would probably make your life easier if you switched to PDO or mysqli and prepared statements. Then you would not have to escape and quote your variables and the mysql_* functions are deprecated anyway.
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= "')";
Put all the values in single quotes.

Categories