I am simply inserting a demo data by ajax form to database. The ajax shows no error but shows blank response when i use console.log(response);.
Php code-
<form role="form" id="signup_form">
<div class="row">
<div class="col-lg-6 col-md-6">
<div class="form-group">
<label class="required">First Name</label>
<div class="input-with-icon">
<input type="text" class="form-control" placeholder="Your First Name"
name="f_name" id="f_name" required>
<i class="ti-user"></i>
</div>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" id="submit" name="submit"
class="btn btn-md full-width btn-theme-light-2 rounded">Sign Up</button>
</div>
</form>
ajax code-
<script>
$(document).ready(function() {
$("#submit").on("click", function(e) {
e.preventDefault();
var f_name = $('#f_name').val();
console.log(f_name); // <--- but this shows the typed data from the form
$.ajax({
url: "homes/php/user-signup.php",
method: "POST",
data: {
"f_name": f_name
},
success: function(response) {
$('#signup_form')[0].reset();
$('#signup').modal('hide');
console.log(response); // <--- this shows blank response
},
error: function(response) {
console.log(response);
}
});
});
});
</script>
mysql --
<?php
session_start();
include_once 'conf.php';
if(isset($_POST['submit'])){
$f_name=$_POST['f_name'];
$query = "INSERT INTO `user_info`(`first_name`) VALUES (':f_name')";
$stmt = $dbcon->prepare($query);
$stmt->bindParam(':f_name',$f_name);
$stmt->execute();
}
?>
You're echoing a script block in the response, which makes no sense in an AJAX context.
Also you're not echoing any content in anything except the pure success case, and you're checking for the wrong variable in $_POST - your AJAX code only sends "f_name" to the server, nothing else.
You also have a typo in your SQL query - :f_name should not in in quote marks within the SQL string.
This should give you more feedback:
<?php
session_start();
include_once 'conf.php';
if(isset($_POST['f_name']))
{
$query = "INSERT INTO `user_info`(`first_name`) VALUES (:f_name)";
$stmt = $dbcon->prepare($query);
$stmt->bindParam(':f_name', $_POST['f_name']);
if($stmt->execute())
{
echo "Signup Successful";
}
else
{
echo "Error - query did not execute correctly. See error logs for details";
//N.B. You should put some code here to log the real error to a file
}
}
else
{
echo "Missing parameters, please try again";
}
?>
If it still doesn't output anything after that, do some more debugging - check your browser's Console and Network tools to see if the request is even succeeding.
Change this $_POST['submit'] to $_POST['f_name']. It will work. you didn't post submit in ajax request.
<?php
session_start();
include_once 'conf.php';
if(isset($_POST['f_name'])){
$f_name=$_POST['f_name'];
$query = "INSERT INTO `user_info`(`first_name`) VALUES (:f_name)";
$stmt = $dbcon->prepare($query);
$stmt->bindParam(':f_name',$f_name);
if($stmt->execute()){
echo "Signup Successfull";
}else{
echo "Insert failed. DB error";
}
}
?>
Related
I have a simple Subscribe form that I want to get the contents of an 'email' input to post to a MySQL db using AJAX. This is successfully creating a record with the date and time but not inserting the email address.
Can anyone see what's wrong with the following please?
form.php
<form id="subscribe" action="?action=signup" method="post" data-abide>
<div class="row collapse">
<div class="large-10 large-centered columns">
<div class="row collapse postfix-radius">
<div class="small-9 columns">
<div class="email-field">
<input type="email" name="email" id="email" placeholder="Your Email Address" required>
<small style="padding-left:10px; "class="error">Please enter a valid email address</small>
</div>
</div>
<div class="small-3 columns">
<input type="submit" id="button" class="button success postfix" value="Subscribe">
</div>
</div>
</div>
</div>
</form>
<span style="display:none;" id="message"><small><i class="fa fa-check" aria-hidden="true"></i> Subscribed</small></span>
<script type="text/javascript">
$(document).ready(function(){
$('#subscribe').submit(function(){
var data = $(this).serialize();
$.ajax({
type: 'post',
url: 'subscribe_insert.php',
data: data,
success: function(data) {
$("#message").fadeIn(250);
}
});
return false;
});
});
</script>
subscribe_insert.php
<?php
include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");
$email = mysql_real_escape_string($_POST['email']);
$date_time = date("Y-m-d H:i:s");
$sql = "INSERT INTO subscribe
(email,
date)
VALUES
('$email',
'$date_time')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Thanks,
John
$(document).ready(function(){
$('#subscribe').submit(function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data)
$.ajax({
type: 'post',
dataType: 'JSON',
url: 'subscribe_insert.php',
data: data,
success: function(data) {
$("#message").fadeIn(250);
}
});
return false;
});
});
replace your code with this then open your browser console and check if the data s getting posted
if you can see the your email there then check if the data is at the server
in you php page copy all the contents from the page and replace
<?php
echo json_encode($_POST)
?>
and once again check console this time you should see data from the server
if both are correct put your original php code back it
Check in your database that email has the correct attributes:
For exaple check that you have at least x characters allowed to be stored, check for the type of the field:
It could be int when it it really should be something like varchar
var_dump details:
form.php is ok for this purpose.
But we are going to modify the php file temporarily to check for "post" error in the email field:
<?php
include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");
$email = mysql_real_escape_string($_POST['email']);
var_dump($email); //dump email value
/* comment this peace
$date_time = date("Y-m-d H:i:s");
$sql = "INSERT INTO subscribe
(email,
date)
VALUES
('$email',
'$date_time')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
*/
?>
Now follow the next steps:
Open chrome
Open your webpage
Hit F12
Check the "Log XMLHttpRequests" checkbox
Send your form and you will se something in the console like: XHR finished loading: POST http://localhost//folder/subscribe_insert.php
Click the logged url of your console
You may see a list of resources (depends of your project)
Click the one that has the subscribe_insert.php title
To your right you will see some tabs click response
If there was some error or some data was echoed from that file (In this case our var_dump) you will see it there.
If you see the email actually printing out It might be a database problem as I started tellong you.
I know there are too many steps but it's very fast to do it, I hope I have helped you, greeting!
The function that this do is when the user clicked the button, it will execute the Ajax codes and then get the value of the input and send it to the PHP file and then send it back to the Ajax code to display the message from the MySQL table.
I tried changing my codes, changing div ids, changing syntax, clearing block of codes but none seems to work.
AJAX
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('input[name=message]').val();
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
HTML UPDATED
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<form method="POST">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</form>
</div>
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
PHP UPDATED
<?php
include 'database/connect.php';
session_start();
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$_POST[message]%' OR '$_POST[message]%_' OR '$_POST[message]_'";
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
echo "Hi ". $_SESSION['name'] .".<br> " . $row['message'];
}
?>
Changes with suggestion(in comment):-
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</div><!-- form not requird -->
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
<!-- Add jquery library so that jquery code wiil work -->
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('#msg').val(); // id is given so use that, its more easy
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
automatedchat_func.php(must be in the same working directory where your above html file exist)
<?php
error_reporting(E_ALL);// check all type of error
ini_set('display_errors',1);// display all errors
include 'database/connect.php';
session_start();
$final_result='';//a variable
if(isset($_POST['newmsg']) && !empty($_POST['newmsg'])){// its newmsg not message
$message = $_POST['newmsg'];
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$message%' OR '$message%' OR '$message'"; // check the change ere
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) { // while needed
$final_result .="Hi ". $_SESSION['name'] .".<br> " . $row['message']."<br>";
}
}else{
$final_result .="Hi please fill the input box first";
}
echo $final_result; // send final result as response to ajax
?>
Note:- your query is still vulnerable to SQL Injection. So read for prepared statements and use them
I am trying to do a simple login through AJAX and it works fine except that after the success callback alerts the response, the browser shows the JSON response like this:
{"status":"success","username":1234}
I have used the same piece of code several times before with no problems, but I think I am missing some knowledge as to why this is happening? There are some modifications of course, but the AJAX part is the same in both PHP and Jquery and I can't figure out what I am doing wrong.
This is the Jquery:
$('#btnLogin').on('click', function(){
login();
});
function login(){
var un = $('#loginUn').val();
var pwd = $('#loginPwd').val();
$.ajax({
url: 'index.php?page=login',
type: 'POST',
dataType: 'json',
data: {'un': un, 'pwd': pwd},
success: function(data){
alert("You are logged in as "+data.username);
},
error: function (request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error+ " DATA: " + data);
}
});
}
The PHP controller:
include_once 'models/login.class.php';
$user = new Login( $dbh );
// If the form is submitted
if(isset($_POST['un'])){
// Check if fields are empty
$fields = array('un', 'pwd');
$error = false; //No errors yet
//Loop trough each field
foreach($fields AS $fieldname) {
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) {
$error = true; //Yup there are errors
}
}
// If there are no errors
if(!$error) {
$un = $_POST['un'];
$pwd = $_POST['pwd'];
$user->checkUser($un, $pwd );
}
}
$view = include_once"views/login-html.php";
return $view;
And finally the model generating the response:
class Login {
private $dbh;
// Connect to database
public function __construct ( $pdo ) {
$this->dbh = $pdo;
}
public function checkUser ($un, $pwd ){
$sth = $this->dbh->prepare('SELECT password, username FROM employees WHERE username = ?');
$sth->execute(array($un));
//Getting the data from db
while($r=$sth->fetch()){
$password = $r['password'];
$username = $r['username'];
}
if($un == $username && $pwd == $password){
$array = array('status' => 'success', 'username' => $username);
// echo "<script>alert('You are logged in as ".$username."');</script>";
// echo "<script>window.location.href='index.php';</script>";
// echo json_encode(array('status' => 'success', 'username' => $username);
$forEcho = json_encode($array);
echo $forEcho;
}else{
echo json_encode(array('status' => 'failure'));
}
exit;
}// End checkUser function
}// End of class
This is the HTML:
<div class="container text-center">
<div class="col-sm-4 col-sm-offset-4">
<h1>Login</h1>
<form role="form" method="post">
<div class="form-group">
<div class="row">
<h3>Username</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-user"></span>
</div>
<input type="text" name="un" class="form-control" id="loginUn" placeholder="Please type in your username">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<h3 id="lblPassword">Password</h3>
<div class="input-group">
<div class="input-group-addon">
<span class="fa fa-key"></span>
</div>
<input type="password" name="pwd" class="form-control" id="loginPwd" placeholder="Please type in your password">
</div>
</div>
</div>
<button id="btnLogin" type="¨button" name="btnLogin" class="btn btn-success">Submit</button>
</form>
</div>
</div>
If somebody could tell me where I am going wrong I would really appreciate it! Have been looking for a solution/explanation with no result for several hours.
EDIT: Added the HTML. The alert in the success callback works just fine, but when closing it the JSON is all that is displayed on a blank screen. Never had this happen to me before.
You have an invalid value for the type attribute:
type="¨button"
… so the button reverts to the default and is a submit button.
You are seeing the results of submitting the form normally instead of using Ajax.
As a short term fix, remove the ¨. In the long term, you should adopt unobtrusive JavaScript as a best practise.
I bet btnLogin is a submit button, huh.. return false or prevent default to prevent the form from submitting..
$('#btnLogin').on('click', function(e){
e.preventDefault();
login();
});
This is embarrassing but I cant seem to figure out why my form wont repost after changing the values.
To be clearer, I have this password recovery form in which user enters the email address. The form is processed in PHP through AJAX and a validation/success message is displayed on the form page.
The issue here is that if the user has entered an invalid email address, it displays the error message but if the user then corrects the email address and tries to submit again, it doesn't process the input unless if the page is explicitly refreshed (in which case it shows the resubmission warning which is very annoying). Is there some property that sets the form and needs to be 'un-set' through code? How can I improve this experience? I have posted the code below.
<form id="pwd_rec_form" method="post" action="">
<div class="row">
<div class="large-6 columns">
<input type="email" required placeholder="Email ID" name="email"/>
</div>
</div>
<div id="val_msg" class="row"></div>
<div class="row">
<div class="large-6 columns">
<input id="submit_button" type="submit" value="Send" class="button"/>
</div>
</div>
<div class="row">
<div class="large-6 columns">
Back to login page
</div>
</div>
</form>
<script>
$(function()
{
$("#pwd_rec_form").submit(function()
{
var formdata = $(this).serializeArray();
var hideMsg = function() {$("#val_msg").hide()};
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "recover-password.php",
data: formdata,
success: function(res)
{
$('#val_msg').html(res);
setTimeout(hideMsg, 5000);
}
});
$("#pwd_rec_form").trigger("reset");
return false;
});
});
</script>
PHP :
<?php
include 'db-connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$conn = getDBConnection();
// Check connection
if (mysqli_connect_errno())
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_connect_error() . '
</div>'
);
exit();
}
$eID = mysqli_real_escape_string($conn, trim(strip_tags($_POST['email'])));
$query = 'SELECT password FROM member_login WHERE email_id = "' . $eID . '";';
$result = mysqli_query($conn, $query);
if($result == FALSE)
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_error($conn) . '
</div>'
);
}
else
{
if(mysqli_num_rows($result) == 0) // User not found.
{
echo('<small class="error">This email address is not registered with us.</small>');
}
else
{
$pswd = mysqli_fetch_assoc($result);
//mail the pswd
echo(' <div data-alert class="alert-box success">
Your password has been successfully sent to your registered email address.
</div>'
);
/* free result set */
mysqli_free_result($result);
}
}
mysqli_close($conn);
}
?>
I think your problem is that you have a submit button, which automatically submits the form and refreshes the page, so your javascript doesn't get used. Try making your submit button a type="button" and then changing your jQuery to $("#pwd_rec_form").click(function() and see if that works.
You could hook the form submit, or if you wanted you can hook the click event of the submit button, prevent the default action and instead do your javascript code. Here is an example hooking the "submit_button" click event:
$(document).ready(function() {
$("#submit_button").click(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
Alternative you can do this:
$(document).ready(function() {
$(form).submit(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
The code above just hooks the form on the submit request, prevents the default action, and then you slap your ajax code in there.
I appreciate your help guys. I knew it was something silly. Turns out the form was getting processed but the validation/success messages were not being displayed as the div element that I was hiding using javascript during the first submission needed to be shown again for the second attempt!
Could you try this :
<script>
$(document).ready(function(){
$('#pwd_rec_form').on('submit', function(e){
e.preventDefault();
// insert AJAX call
});
It worked for me, the event is trigged on each click.
Best regards,
im quite bad at javascript, and i am trying to make a AJAX call, but i get my value from a form feild, and it just refreshes the page, cant even observe if the AJAX call is succesfull.
Here is my HTML:
<form class="form-horizontal" id="subscribe-form" name="subscribe-form" onSubmit="return subscribe();">
<fieldset>
<p>
Subscribe
</p>
<div class="input-prepend input-append">
<input name="subscribwEmail" class="span2" id="InputEmail" type="email" placeholder="Email">
<input type="submit" class="btn btn-inverse" />
</div>
</fieldset>
</form>
JS:
function subscribe() {
var emailForm = $('#subscribwEmail').val();
$('#subscribe-form').hide(); // hide email form
$('#subscribeDiv').prepend('<img id="process" src="http://www.mydomain.com/assets/img/process.gif" />')
$.ajax({
type: "POST",
url: "../../actions/ajax-subscribe.php",
data: {
email: emailForm
},
dataType: "json",
success: function (data) {
if (data[0] == 1) { // test if response was 1 or 2
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>Thank you for subscribing!</p>');
} else {
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>There was an error subscribing the email.</p>');
}
}
})
};
ajax-subscribe.php
<?php
include ('phpfunctions.php');
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('ERROR WITH SQL CONNECTION CONTACT ADMIN');
$email = cleanString($con, $email);
$query = "INSERT INTO `subscribers` (`email`, `ip`) VALUES ('$email', '$ip');";
if ($result = mysqli_query($con, $query)) {
echo json_encode(1); // all ok inserted
} else {
echo json_encode(0); // failed
}
?>
You do not cancel the click event so the form submits.
Add return false; to the end of your subscribe method.
You have to return false from your subscribe method
Also you can validate the email, if it is invalid, you can stop sending subscribe by return false
You can also disable your submit button. (formObj comes with subscribe parameter)
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
But you have to enable it if something goes wrong.