Passing variable back to page with ajax - javascript

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"]
}
}
});

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

Return mysql fetch data and insert into form field value

i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});

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.

ajax contact form does not send email

All day i trying to solve the problem but without success.
The form does not send a message and not written an error.
form.html
<div class="ok" id="ok"></div>
<div id="data">
<div id="alert" class="alert_ig"></div>
<form id="form" class=" clearfix" method="POST" action="">
<div class="col-sm-12">
<div class="form-group">
<input name="name" type="text" id="name" value="{$smarty.cookies.nameuser}" class="form-control" placeholder="Name"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<input name="email" type="email" id="email" value="{$smarty.cookies.emailuser}" class="form-control" placeholder="E-mail"/>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<textarea id="message" class="form-control" rows="5" name="text" placeholder="Message"></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<button style="margin-top:10px" id="submit" type="submit" class="bot_g">Send</button>
</div>
</div>
</form>
<script>
$(document).ready(function() {
$('#submit').click(function(e){
var form = $(this);
var error = false;
if (!error) {
var data = form.serialize();
$.ajax({
type: 'POST',
url: '{$home}/system/modules/contacts/send.php',
dataType: 'json',
data: data,
success: function(data){
if (data.error.length > 0) {
$('#alert').html(""+data['error']+"");
$('#email').addClass("fill");
} else {
$('#ok').html('send.');
$( "#data" ).css( "display","none" );
}
},
return false;
)};
});
</script>
</div>
send.php
<?php
require_once '../../inc/core.php';
$name=Text(trim($_POST['name']));
$email=Text(trim($_POST['email']));
$subject=Text(trim($_POST['subject']));
$text=Text(trim($_POST['text']));
if(empty($name)){
$json['error'] = 'Come on, you have a name don\'t you?';
echo json_encode($json);
exit;
}
if (mb_strlen($name) < 2 || mb_strlen($name) > 250){
$json['error'] = 'Your name must consist of at least 2 characters!';
echo json_encode($json);
exit;
}
if(empty($email)){
$json['error'] = 'No Email, No Message!';
echo json_encode($json);
exit;
}
if (mb_strlen($email) < 5 || mb_strlen($email) > 64){
$json['error'] = 'Your email must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$json['error'] = 'Unknown characters in your e-mail!';
echo json_encode($json);
exit;
}
if(empty($subject)){
$json['error'] = 'Um...yea, you have to write something to send this form.';
echo json_encode($json);
exit;
}
if (mb_strlen($subject) < 5 || mb_strlen($subject) > 250){
$json['error'] = 'Your subject must consist of at least 5 characters!';
echo json_encode($json);
exit;
}
if (mb_strlen($text) < 2 || mb_strlen($text) > 10000){
$json['error'] = 'Thats All? Really?';
echo json_encode($json);
exit;
}
$mailer = new phpmailer();
$mailer->ContentType = "text/html";
$mailer->From = $email;
$mailer->Subject = 'New message from '.$home;
$mailer->Body ="Subject: ".$subject."<br/>
Name: ".$name."<br/>
E-mail: ".$email."<br/>
".nl2br($text);
$mailer->AddAddress($setup['emailadmin'], '');
$mailer->Send();
$json['error'] = 0;
echo json_encode($json);
?>
When is my problem with this code?
I must use this send.php format, but may to change ajax and html form to working...
thanks
var form = $(this);
In this line $(this); refers to the submit button so var form, stores your submit button instead of the form element itself.
You may not see an error on the client-side, but if you try to debug the data sent to your server-side you will see something is wrong.
Try replacing $(this) with the selector that matches your form element.
Also, if you want to inform your users when the server returns an error like a 500 error for example, you can add an error callback to your $ajax function, along with the success callback you already have.
Have a look here http://api.jquery.com/jquery.ajax/ for the documentation.
Also add e.preventDefault() at the end of your event handler, to prevent the default action of submitting the form if you want to do an ajax submit.

AJAX request saves to database but alerts failed

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

Categories

Resources