trying to store simple email data from website to mysql database, i've written the code however it is not working and i can't figure it out
<form class="subfield">
<input type="text" id="emailInput" name="email" type='email' placeholder="Enter Your Email here" required>
<input type="submit" id="inputSubmit" value="Subscribe">
<span id="st">Email Subscribed!</span>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#inputSubmit').click(function(){
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
});
});
</script>
<?php
//insert.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["email"]))
{
$email = mysqli_real_escape_string($connect, $_POST["email"]);
$sql = "INSERT INTO `emails_list`(`email`) VALUES ('".$email."')";
if(mysqli_query($connect, $sql))
{
echo "email Subscribed";
}
}
?>
when submit button is clicked it redirects to the home page as it should and the url also shows the ?email= part but no data is stored on the database also seems no echo is sent from php
EDIT : i noticed the files are saved as index.php instead of index.html is it necessary to save as index.php
possibly way to to prevent deafult browser action. Then call ajax request on submit.
$(document).ready(function(){
$('#inputSubmit').click(function(e){
e.preventdefault();
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
});
});
There are two thing you can do about:
Use a button instead of submit
this:
<input type="submit" id="inputSubmit" value="Subscribe">
to:
<input type="button" id="inputSubmit" value="Subscribe">
use preventDefault Method
$(document).ready(function() {
$("#inputSubmit").click(function(e) {
e.preventDefault();
var email = $("#emailInput").val();
$.ajax({
url: "form_process.php",
method: "POST",
data: { email: email },
success: function(data) {
$("form").trigger("reset");
$("#st")
.fadeIn()
.html(data);
setTimeout(function() {
$("#st").fadeOut("Slow");
}, 2000);
}
});
});
});
$(document).ready(function(){
$('#inputSubmit').click(function(e){
e.preventdefault();
var email = $('#emailInput').val();
$.ajax({
url:"form_process.php",
method:"POST",
data:{email:email},
success:function(data){
$("form").trigger("reset");
$('#st').fadeIn().html(data);
setTimeout(function(){
$('#st').fadeOut("Slow");
}, 2000);
}
});
return false;
});
});
Related
the problem is that i am unable to insert data in my database without reloading
i have tested it without the note_sql.js and my note_sql.php works fine but there seems to be a problem in my js file if some body could point me in the right direction it would be wonderful
Index.php
<form id="noteform" action="note_sql.php" method="POST">
<input type="text" name="note"></input>
<input id="sub" type="submit" value="Save Note" />
</form>
<span id="result_note"><span>
<script type ="text/javascript" src="jquery/note_sql.js"></script>
note_sql.js
$("#sub").click(function(){
var data = $("#noteform: input").serializeArray();
$.post($("#noteform").attr("action"),data,function(info){$("result_note").html(info); });
clearInput();
});
$("#noteform").submit(function(){
return false;
});
function clearInput(){
$("#noteform :input").each(function(){
$(this).val('');
});
}
Use Jquery Ajax the working code is given below :
please add ID to Note Form Element :
<pre>
<script>
$(document).ready(function () {
$("#sub").click(function () {
var name = $("#note").val();
var message = $("#message").val();
$.ajax({
type: "post",
url: "note_sql.php",
data: "name=" + name,
success: function (data) {
alert(data);
}
});
});
});
</script>
</pre>
Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});
I know this has been asked before, but I can seem to find an solution that fixes the problem in my case. I'm trying to post data to a Mysql database with an an Ajax post
HTML
<form action="" method="post">
<input type="text" id="message" name="message">
<<input type="submit" value="Send" id="submit">
</form>
Ajax post
$(document).ready(function(){
$("#submit").click(function(){
var message = $("#message").val();
var data = "message=" + message;
console.log(data);
if(message != ''){
console.log(data);
$.ajax({
type: "POST",
url: "classes/messages.php",
data: data,
succes: function(){
alert("succes");
}
});
}
return false;
});
});
PHP code
class messages{
function getMessages(){
$con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
$message = $_POST['message'];
mysqli_query($con, "INSERT INTO messages(message, time, user_id)
VALUES('$message', 'now()', '12')")or die(mysqli_error($con));
mysqli_close($con);
}
}
$messages = new Messages();
$messages->getMessages();
Everytime I submit the form nothing happends, not even an php error appears. I've checked the Ajax post and both console.logs return the correct value, so I think the variable is reachable.
I've also checked if the php function is executed at all, which is the case.
Try this
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var message = $("#message").val();
var data = "message=" + message;
console.log(data);
if(message != ''){
console.log(data);
$.ajax({
type: "POST",
url: "classes/messages.php",
data: data,
success: function(){
alert("succes");
}
});
}
return false;
});
});
</script>
</head>
<body>
<form action="" method="post">
<input type="text" id="message" name="message">
<input type="button" value="Send" id="submit">
</form>
</body>
</html>
and
<?php
class messages{
function getMessages(){
$con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
$message = $_POST['message'];
mysqli_query($con, "INSERT INTO messages(message, time, user_id)
VALUES('$message', 'now()', '12')")or die(mysqli_error($con));
mysqli_close($con);
}
}
$messages = new Messages();
$messages->getMessages();
Basically I changed input type='button' from `'submit' . Since it was a submit button, the ajax call was never done, instead the form was submitting.
You could try this shorthand method instead:
var message = "message=" + $("#message").val();
$("#submit").on("click", function(ev)){
$.post("classes/messages.php", {message: message}, 'json').done(function (data, textStatus, jqXHR) {
console.log("succes");
}).fail(function () {
console.log("Fail");
return false;
}).always();
}
Use on it's better and recommended than just trigger the function on the selector itself.
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
To begin, I'm working with 3 languages. HTML, Javascript and PHP. I'm unable to pass user inputted textarea text to a PHP variable which would be used as a message in an email that would be sent out. What I believe to be the problem is that my textarea is actually in a modal window and for some reason I think that is what is screwing things up.
Here is my HTML Code:
<div class="rejectModal" title="rejectModal" id="rejectModal" style="display: none; padding:15px ">
<form name="rejectForm" action="">
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43">{$rejectAreaNote}</textarea>
<input type="button" value="Reject" class="btn success" id="submitReject" name="Reject" />
<input class="btn" type="reset" value="Cancel" id="btnCancelSaveModal" />
</form>
</div>
JS Code:
$(function() {
$(".submitReject").click(function() {
// validate and process form here
$('.error').hide();
var rejectAreaNote = $("textarea#rejectArea").val();
var noteLength = rejectAreaNote.length;
if (rejectAreaNote == "" || noteLength < 5) {
$("label#rejectArea_error").show();
$("textarea#rejectArea").focus();
return false;
}
var dataString = rejectAreaNote;
alert (dataString);
//return false;
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: {
"Reject" : "Reject",
"rejectAreaNote" : "rejectAreaNote"
},
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Submitted!");
}
});
return false;
});
});
What creates the Modal (JS):
$('.rejectModal').css("background", "lightblue");
$('#btnRejectDocument').bind(isTouchScreen ? "touchstart" : "click", function(){
if (!gsSelection.unselectElem()) return false;
$('.rejectModal').dialog({
modal:true,
resizable:false,
width: 400,
}).removeClass("ui-widget-content");
$(".ui-dialog-titlebar").hide();
return;
});
$('#btnRejectDocumentModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
$('#btnCancelSaveModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
PHP Code:
if(isset($_POST['Reject'])&&$_POST['Reject']=='Reject')
{
$isReject = true;
RejectAction($DocumentID, $ClientName, $ClientEmail);
$smartyvalues["isReject"] = $isReject;
$smartyvalues["RejectMsg"] = "successfully rejected!";
}
Also pretty new tot his
Any help is greatly appreciated.
Textarea does not have a value attribute. If you want to add a value to your textarea, add it inside the tag: <textarea>value</textarea>
So try changing it to this:
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43"/>{$rejectAreaNote}</textarea>
if(isset($_POST['Reject']) ...
You are not sending this to the server. Instead, you're sending "dataString", which is just the text from textarea. What you should do instead is send an object with needed fields:
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: {
"Reject" : "Reject",
"rejectAreaNote" : "rejectAreaNote"
},
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Submitted!");
}
});
I'm still not sure what your code is supposed to do and how it glues together, but this here is definitely wrong.