AJAX request saves to database but alerts failed - javascript

I have a bootstrap modal contact form which uses AJAX and PHP to save the information sent by a user to a database:
<div class="modal fade" id="contact" role="dialogue">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<form id="myform" role="form">
<div class="form-group">
<label for="name">Name: </label>
<input type="name" name="name" class="form-control" id="name" >
</div>
<div class="form-group">
<label for="email">Email: </label>
<input type="email" name="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="msg">Message: </label>
<textarea class="form-control" name="msg" id="msg" rows="10"></textarea>
</div>
<!-- <a class="btn btn-primary" data-dismiss="modal">Close</a> -->
<button id="sub" type="submit" name="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
</div>
When I submit the form the page alerts that the AJAX request has failed but yet the information still saves to the database!? anybody know where I'm going wrong, I have attached my script.js and send.php file below:
Javascript/Ajax file:
$(document).ready(function(){
$('#myform').submit(function(){
$.ajax({
type: 'post',
url: 'send.php',
dataType: 'json',
async: true,
data: $('#myform').serialize(),
success: function(msg){
alert("It was a success");
return false;
},
error: function(jqXHR, textStatus, errorThrown){
alert("Fail");
console.log(jqXHR + '-' + textStatus + '-' + errorThrown);
return false;
}
});
});
});
PHP file for processing and saving to DB
<?php
include 'connect.php';
if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
$sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);
$stmt->execute();
echo "done";
}else{
echo "Nothing posted";
}
?>
P.S No errors are output to the console, just the alert saying failed.

according to your javascript, your ajax is expecting to receive a json result, look at this line
dataType: 'json',
but in your php code you are only echoing a string
echo "Nothing posted";
two solutions , delete this code in your javascript dataType: 'json'
or return a json in your php
$data['result'] = "nothing posted";
echo json_encode($data);

As Luis suggests, try to add proper header to the php file which saves to the database and make the output json object like so:
<?php
include 'connect.php';
//The json header
header('Content-type: application/json');
header("Content-Disposition: inline; filename=ajax.json");
if(isset($_POST['name'])&&($_POST['email'])&&($_POST['msg']))
{
$sql = "INSERT INTO details (name, email, message) VALUES (:Name, :Email, :Msg)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':Email', $_POST['email'], PDO::PARAM_STR);
$stmt->bindParam(':Msg', $_POST['msg'], PDO::PARAM_STR);
$stmt->execute();
$result = array('success'=>true, 'message'=>'The data has been saved successfuly');
} else {
$result = array('success'=>false, 'message'=>'Can\'t save the data');
}
//Also is a good practice to omit the php closing tag in order to prevent empty characters which could break the posted headers
echo json_encode($result);
I would use the following alias instead of $.ajax, but it's a personal preference:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault(); //Prevent form submission, so the page doesn't refresh
$.post('send.php', $(this).serialize(), function(response){
console.log(response); //see what is in the response in the dev console
if(response.success == true){
//success action
//...some code here...
} else {
//error action, display the message
alert(response.message);
}
});
});
});
Hope that helps

Related

Ajax post fail with php file [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 3 years ago.
I'm trying to use a php api with ajax to create a new contact. When I want to use the postContact.php file with ajax the query fail every time but if I write the post url directly in the browser it'll work.
I looked over internet but I didn't find a solution.
I looked in in the php function directly
I checked if the data format was good
I enter directly the data in the ajax code
I change the contentType and the dataType
I looked jQuery Ajax POST example with PHP before posting here
I remove datatype and content-type
I change this.method by "POST" and this.action by the url to the api
HTML Form to add contact
<form id="addContact_form" action="php/postContact.php" method="POST">
<div class="modal-body">
<div class="form-group">
<label>Nom</label>
<input id="addContact_nom" name="nom" type="text" class="form-control" required/>
</div>
<div class="form-group">
<label>Prénom</label>
<input id="addContact_prenom" name="prenom" type="text" class="form-control" />
</div>
<div class="form-group">
<label>Fonction</label>
<input id="addContact_fonction" name="fonction" type="text" class="form-control" />
</div>
<div class="form-group">
<label>Téléphone</label>
<input id="addContact_tel" name="telephone" type="number" class="form-control" />
</div>
<div class="form-group">
<label>Adresse Mail</label>
<input id="addContact_mail" name="couriel" type="email" class="form-control" />
</div>
<label>Lycée</label>
<!--this is filled with an ajax function when the modal show up-->
<select id="addContact_lycee" name="id_lycee" class="custom-select" required>
<option selected>Sélectionner un lycée</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-perso-success">Save changes</button>
</div>
</form>
Ajax AddContact
$("#addContact_form").submit(function(event){
$('#addContactDialog').modal('hide');
loader('show','Sauvegarde en cours');
event.preventDefault();
console.log(this.action+$(this).serialize()); //this print https://..../php/postContact.phpnom=charle%20&prenom=edouard&fonction=eleve&telephone=0000&couriel=sdf%40dfg.g&id_lycee=2
$.ajax({
method: this.method,
url: this.action,
data: $(this).serialize(),
error: function(jqXHR, textStatus, errorThrown){
loader('hide');
errorAlert(errorThrown);
},
success: function (data) {
loader('hide');
var message = data.message;
if(message.indexOf('failed') != -1){
errorAlert(data.message);
}else{
successAlert(data.messages);
}
}
});
});
php file called by ajax
this is not mine so I don't really know how it's work
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once 'lycee.php';
include_once 'bdd.php';
$bdd = getConnexion();
$lycee = new lycee($bdd);
// get posted data
$nom = $_GET['nom'];
$prenom = $_GET['prenom'];
$fonction = $_GET['fonction'];
$telephone = $_GET['telephone'];
$couriel = $_GET['couriel'];
$id_lycee = $_GET['id_lycee'];
$lycee->postContact($nom, $prenom, $fonction, $telephone, $couriel, $id_lycee);
?>
function PostContact()
public function postContact($nom, $prenom, $fonction, $telephone, $couriel, $id_lycee){
$req2 = $this->conn->prepare ('SELECT * FROM contact WHERE lycee_contact=:id_lycee');
$req2->execute(array('id_lycee' => $id_lycee));
$donnees2 = $req2->fetchAll();
$num = count($donnees2);
//if alerady a contact to this entry -> update
if($num > 0){
$req = $this->conn->prepare('UPDATE contact SET nom=:nom, prenom=:prenom, fonction=:fonction, telephone=:telephone, couriel=:couriel WHERE lycee_contact=:id_lycee');
$result = $req->execute(array('nom' => $nom, 'prenom' => $prenom, 'fonction' =>$fonction, 'telephone'=>$telephone, 'couriel'=>$couriel, 'id_lycee' => $id_lycee));
if($result){
echo '{';
echo '"message": "Contact a été sauvegardé"';
echo '}';
}else{
echo '{';
echo '"message": "Une erreur est survenue, modification échoué"';
echo '}';
}
}else{ //cerate contact
$req = $this->conn->prepare('INSERT INTO contact SET nom=:nom, prenom=:prenom, fonction=:fonction, telephone=:telephone, couriel=:couriel, lycee_contact=:id_lycee');
$result = $req->execute(array('nom' => $nom, 'prenom' => $prenom, 'fonction' =>$fonction, 'telephone'=>$telephone, 'couriel'=>$couriel, 'id_lycee' => $id_lycee));
if($result){
echo '{';
echo '"message": "Contact a été sauvegardé"';
echo '}';
}else{
echo '{';
echo '"message": "Une erreur est survenue, création échoué"';
echo '}';
}
}
}
When the ajax method is executed it goes to the success callback but it returnd the api's error message and the data aren't add
I expect the ajax function to call execute the postContact.php file from the api to save a contact
I solved my problems thanks to arkuuu.
his anwser :
Your form says method="post", but php tries to fetch the values from $_GET. Try >changing $_GET['...'] to $_POST['...']
I follow his instruction and now it's work

Php Ajax Form is not submitting

Hey guys I am creating a newsletter sign-up form and trying to submit it with AJAX..
Here is my form:
<div id="form-content">
<form method="POST" id="news-form" name="newsletter">
<div class="bd-input-2 form-group">
<input type="email" name="newsletter_email" placeholder="Enter your email address" required />
</div>
<div class="form-group">
<button type="submit" name="newsletter">Submit</button>
</div>
</form>
</div>
And this one is my JS file in same page as form:
$('#news-form').submit(function(e){
e.preventDefault();
$.ajax({
url: 'newsletter-submit.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#form-content').fadeOut('slow', function(){
$('#form-content').fadeIn('slow').html(data);
console.log(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
On console nothing is displaying not even an error just an empty line.
And my newsletter-submit.php file :
<?php
if(isset($_POST['newsletter'])){
$newsletter_email = filter_var($_POST['newsletter_email'],FILTER_VALIDATE_EMAIL);
if(filter_var($newsletter_email, FILTER_VALIDATE_EMAIL)){
$newsletter_email = filter_var($newsletter_email, FILTER_VALIDATE_EMAIL);
$em_check = sqlsrv_query($con, "SELECT email FROM newsletter_signups WHERE email='$newsletter_email'",array(), array("Scrollable"=>"buffered"));
$num_rows = sqlsrv_num_rows($em_check);
if($num_rows > 0){
echo "<br/><p style='color: #fff;'>Email exist in our newsletter list.</p>";
}else{
$query = "INSERT INTO newsletter_signups (email) VALUES ('{$newsletter_email}')";
$insert_newsletter_query = sqlsrv_query($con,$query);
echo '<br/><p style="color: green;">Thank you for sign up in our newsletter</p>';
}
}
}
?>
But if I add any code after php tags e.g Hello world that is displayed after the submission.
My php code was working before AJAX file
Your input field is named newsletter_email and in your php you are checking for isset($_POST['newsletter']) which is always false.

To display data in the fields in the modal retrieved from the mysql database

Friends I am submitting the form on clicking the submit button and simultaneously i am displaying the just submitted data in the modal.So as soon as i hit the submit button ,the data gets submitted and a modal appears with the data just submitted.Everything is working fine with my code but the only problem that the data does not gets displayed in the modal.
Here is the code for submitting the form-
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(msg){
$('input[type="text"], textarea').val('');
$('#entrysavedmodal').modal('show');
},
error: function(){
alert("failure");
}
});
});
Here is modal which gets displayed when i click on submit button-
<div id="entrysavedmodal" class="modal fade" role="dialog">
<div class="modal-dialog" style="width:1000px;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Saved Entry</h4>
</div>
<div class="modal-body">
<form class="form-horizontal savedform" id="savedform">
<div class="form-group">
<label class="control-label col-xs-2">Date:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="datepreview" name="datepreview"
value = "<?php
include('db.php');
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$date = $rows['date'];
echo $date;
?>" readonly /> //this field does not show anything and none of the fields show any data.
</div>
<label class="control-label col-xs-2">v_no:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="v_nopreview" name="v_no" autocomplete="off" readonly /> //same problem
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" id="print" name="print" >Print</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
Date field does not show the date value from database and v_nopreview field also does not show anything.
I have tried to give as much details as possible but in case if you need anything then let me know.Please let me know why the data is not being displayed inside the input fields in modal.
Thanks in advance.
Edited part
Here is the data1_post.php code-
<?php
include('db.php');
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
echo "saved";
}
else
{
echo "not saved";
}
?>
As I understand, you expect execution of php code each time after js event. But PHP is a server-side language, it interprets only once, when you request the pages.
So your php code will load some content form DB after refreshing, then you clear input's value before displaying model and as it can't be executed again - you see empty modal.
I recommend you to return saved data from "data1_post.php" and than process it in success callback
UPDATE
if you want to present saved data, your php code would look like the following
include('db.php');
$response = ["success" => false];
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$response = ["success" => true, "date" => $rows['date']];
}
header('Content-type: application/json');
echo json_encode($response);
and js
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(response){
$('input[type="text"], textarea').val('');
if (response.success) {
$('#datepreview').val(response.date);
$('#entrysavedmodal').modal('show');
} else {
alert("failure");
}
},
error: function () {
alert("failure");
}
});
});

Passing variable back to page with ajax

I have a page (form.php) that uses ajax to post some form data to a page (insert.php) which is then inserted into a mysql database.
I now want to be able to do a simple equation on insert.php and return the result as a variable back to form.php. Can anyone tell me how I return $variable back to form.php as a variable that I can then use?
Form.php
//Stripped down for ease of reading
<script>
$(document).ready(function(){
$("#message").hide();
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('insert.php', formdata,
function(data){
$("#message").html(data);
$("#message").fadeIn(500);
return false;
});
});
</script>
//The Form
<form class="form-inline" action="" id="myform" form="" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="bill_cost"></label>
<div class="col-md-8">
<input id="bill_cost" name="bill_cost" type="text"
placeholder="Bill Cost" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button id="submitButtonId" name="submit1"
class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>
<div id="message">
insert.php
<?php
//Connection script would be here
$bill_cost=$_POST['bill_cost'];
//Insert into Database
$stmt = $db_conx->prepare('INSERT INTO mytable set bill_cost=?);
$stmt->bind_param('s',$bill_cost);
$stmt->execute();
if($stmt){
//Count Rows
$sql="SELECT bill_cost FROM mytable";
$query = mysqli_query($db_conx, $sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($query);
//Do some maths (for example )
$variable=$rowcount/100
//echo message BUT how to send it as a variable?
echo "<h1>Answer is ".$variable."</h1>";
}
else{ echo "An error occurred!"; }
?>
If you want to send data which shall be parsed by your script, you should send your data as json. Sent every output as json, even the errors. For that you will have to send the content-type header. E.g:
// sending output
header('Content-Type: text/json');
echo json_encode(array("my_var" => "This is the content of the var"));
or sending an error:
// or sending error
header('Content-Type: text/json');
echo json_encode(array("error" => "This is my error"));
On the client side you can use $.getJSON (Documentation) to automatically parse the response as json:
// send request and get response
$.getJSON("insert.php", formdata, function(data) {
// check for errors
if (typeof data["error"] == "undefined") {
// check if my_var is set?
if (typeof data["my_var"] != "undefined") {
// use data["my_var"]
}
}
});

issue with ajax login script

I'm very new to ajax, and I'm trying to make a login script that doesn't require a page reload - it's working well except I attempt to set a session variable on the processing page, but no session variable is set.
My form:
<div class="form-bottom">
<form role="form" class="login-form">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="submit" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
<? echo $_SESSION['Name']; ?>
</div>
My ajax:
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+ username + '&password=' + password;
if(username=='' || password=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
});
}
return false;
});
});
</script>
My php script:
include('./static/config.php');
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
I was able to get it working the way I wanted it to.
Form:
<div id="box">
<div class="row">
<div class="col-sm-6 col-sm-offset-3 form-box">
<div class="form-top">
<div class="form-top-left">
<h3>Log-in</h3>
<span id="error" class="error"></span>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div id="box" class="form-bottom">
<form class="login-form" action="" method="post">
<div class="form-group">
<label class="sr-only" for="username">Username</label>
<input type="text" name="username" placeholder="Username..." class="form-username form-control" id="username">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" name="password" placeholder="Password..." class="form-password form-control" id="password">
</div>
<input type="submit" id="login" class="btn" style="width:100%;background-color:lightblue;" value="Log In" id="login"/>
</form>
</div>
</div>
</div>
</div>
AJAX Code:
<script src="js/jquery.min.js"></script>
<script src="js/jquery.ui.shake.js"></script>
<script>
$(document).ready(function() {
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajax/login.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');},
success: function(data){
if(data)
{
window.setTimeout(function () {
location.href = "index.php";
}, 3000);
}
else
{
$('#box').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
PHP (ajax/login.php):
<?php
include("../static/config.php");
session_start();
if(isSet($_POST['username']) && isSet($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($con,$_POST['username']);
$password=mysqli_real_escape_string($con,$_POST['password']);
$result=mysqli_query($con,"SELECT Name FROM techs WHERE Username='$username' and Password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
$_SESSION['Name']=$row['Name'];
echo $row['Name'];
}
}
?>
Since you've stated you're very new to Ajax, you start off pretty well.
There are however a couple of things to know how this works.
You want to avoid a page refresh, yet you don't print out any responses because you're not returning anything in the ajax request. You instead set a session variable which will show up at the next page request (so a refresh)
$.ajax({
type: 'POST',
url: 'ajax/login.php',
data: { username: $("#username").val(), password: $("#password").val() },
success: function (data) {
$('.form-bottom').html(data); // here we replace the form with output of the ajax/login.php response.
}
});
And for the PHP side of things:
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
if(($result = mysqli_query($con, $sql)) != false){ // always verify if your query ran successfully.
if(mysqli_num_rows($result)){ // or compare with == 1, but assuming a username is unique it can only be 1 so it equals to true.
echo mysqli_fetch_assoc($result)['name']; // index, columns, etc should always be lower cased to avoid confusion.
// Obviously you can store it in a session
// But for now just output the data so we can use it as our response.
// json is very usefull with sending large amounts of data.
}
}
The idea of Ajax is that you can request an update, but you need to update your page with javascript manually in order to make it work.
I think you forget to start the session.So start the session at the top of your script. Hope it will help.
session_start();
include('./static/config.php');
if(isset($_POST)) {
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$sql = "SELECT Name FROM techs WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($con, $sql);
$exists = mysqli_num_rows($result);
if($exists == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['Name'] = $row['Name'];
}
}
3 things you could try:
On the page where you are trying to set the session variable you would have to use proper php opening tags like <?php
Second thing is that you would have to put a value in your session like $_SESSION['hello'] = 'hello';
Third thing, on every page where you handle your session you would have to call <?php session_start(); ?> for it to work.
Goodluck!

Categories

Resources