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
Related
I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});
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"]
}
}
});
I'm a beginner attempting to create a HTML webpage. I'm using a free online template and trying to create a Contact Page. The contact calls a php script to send an email of the captured fields. I can get this to work when I send the email as pure php with no javascript or ajax. However when I try to use the javascript with the ajax code, the contents of the web form are not being passed. Two near identical issues have been raised here but I am finding the javascript to complicated for myself to understand as a beginner. The slight differences in the js has resulted in hours of trying to resolve without success.
js deleting submitted form data
PHP form post data not being received due to jQuery
The HTML code is
<div class="col-md-4 col-sm-12">
<div class="contact-form bottom">
<h2>Send a message</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id">
</div>
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Your text here"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
The PHP script is called sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email#email.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
The javascript is as follows
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $.post(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contacting us. We will reply as soon as possible.</p>').delay(3000).fadeOut();
});
});
There are two issues, the first being that the form data doesnt pass when using the javascript code. The second is that it displays the message twice and sends two emails. I think the second issue is related to the php script calling the function again.
Help & guidance will be really appreciated, I am a beginner only attempting a small challenge.
The mail form appears to be deliberately disabled. It took me a while to fix it.
The code below will make it work. I hope this helps.
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contacting us. We will reply as soon as possible.</p>').delay(3000).fadeOut();
});
});
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
I'm using jQuery Ajax to post the data and display the success message accordingly.
Below is the code :
Javascript
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.3.2.min.js">
</script>
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var postForm = { //Fetch form data
"name": $("#name").val(),
"element_4_1": $("#element_4_1").val(),
"element_4_2": $("#element_4_2").val(),
"element_4_3": $("#element_4_3").val(),
"email": $("#email").val(),
"input4": $("#input4").val(),
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'contact.php', //Your form processing file url
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
console.log("inside success3") ;
$("#stage").text(data);alert(data);
if (!data.success) { //If fails
if (data.errors) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors); //Throw relevant error
console.log("inside failure") ;
}
} else {
console.log("inside success") ;
$('#stage').fadeIn(1000).append('<p>' + data.posted + '</p>');
console.log("inside success2") ;
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
HTML
<form class="contact-form" method="post">
<h4 style="padding-top:8px;">Your email address will not be published. Required fields are marked <font color="red">*</font></h4>
<label>Name<font color="red">*</font></label><br>
<input class="form-control" style="height:35px;width:230px;border-radius:4px;" required type="text" name="name" id="name"/><br>
<label>Phone<font color="red">*</font></label><br>
<span>
<input id="element_4_1" name="element_4_1" class="element text" size="3" maxlength="3" value="" type="text"> -
</span>
<span>
<input id="element_4_2" name="element_4_2" class="element text" size="4" maxlength="4" value="" type="text"> -
</span>
<span>
<input id="element_4_3" name="element_4_3" class="element text" size="10" maxlength="10" value="" type="text" required >
</span>
<br><br>
<label>Email<font color="red">*</font></label><br>
<input id="email" class="form-control" style="height:35px;width:230px;border-radius:4px;" required type="email" name="text"/><br>
<label for="input4">Message</label>
<textarea name="contact_message" class="form-control" rows="4" id="input4"></textarea>
<p> </p>
<button type="submit" style="margin-left:65px;"class="btn btn-large btn-info" id="button">Submit</button>
</form>
PHP Server Side
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$errors = array();
$form_data = array();
header('Content-type: application/json');
echo json_encode($form_data);
$name=$_POST['name'];
$phone=chop($_POST['element_4_1']);
$phone.=chop($_POST['element_4_2']);
$phone.=chop($_POST['element_4_3']);
$email=chop($_POST['email']);
$message1=chop($_POST['input4']);
if ($name && $phone && $email) {
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: sales#test.com \n";
$recipient= "test#test.in";
$subject="Online Enquiry ";
$message="\nName : $name\n";
$message.="\nPhone : $phone\n";
$message.="\nEmail ID : $email\n";
$message.="\nMessage : $message1\n";
//send auto-reply
$subject_reply="Thank you for contacting us";
$message_reply="Thank you for contacting us. We will get back to you shortly.";
//mail($email, $subject_reply, $message_reply, $headers);
//Send Mail
//===========
if(isset($recipient, $subject, $message, $headers)) {
error_log($message);
$form_data['status'] = 'success';
error_log($form_data['status']);
} else {
$form_data['status'] = 'error';
error_log($form_data['status']);
}
}
?>
Now everything works fine, but I'm not able to send the success message from the server side to client side. How can I get the success message displayed in the client page. In the client side javascript when I print data in alert box I see an empty box. How can I pass the data variable from server side to client side.
Try
echo "<script>$('#id or .class').html('error or success message here ');</script>";
The output of the PHP (created using echo or print or similar) is the data you pass to your calling Javascript.
In your PHP code you create an emtpy array() in your variable $form_data and then you output this empty array using echo json_encode($form_data). The result on client side will be an empty array, which is not surprising to me.
Bottom line: Everything you output in your PHP will end up as data in the success handler of your Ajax call.