I have a jQuery variable that contains HTML and values from a form. I would like to send it via email using a seperate php file with #mail.
I am trying to send this variable with the jQuery $.ajax function on form submit but it doesn't send the variable to the php file and therefore, no email is sent.
Here is my code
jQuery :
$('form').submit(function(){
var foo = '<p>Some message</p>';
$.ajax({
url: '/send.php',
type: 'post',
data: {foo : foo},
success: function() {
alert('email sent!');
}
});
return false;
});
send.php :
<?php
$email_to = "XXX";
$email_from = "YYY";
$email_message = $_POST["foo"];
$email_subject = "[Email subject]";
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
I tried to echo the foo variable in send.php and removing return false; in the jQuery but The variable doesn't seem to pass to the file and nothing is displayed.
What am I doing wrong?
Your code is OK! We are supposing your PHP web server is working, So the 2 only possible error are:
url: '/send.php'
Are you sure send.php is in the root of your domain? Like
http://localhost/send.php
The second possibility is that you a have a previous javascript fatal error, so your ajax lines will never be readed...
How to debug?
1 - Are your pages refreshing when you post your form? If yes, there's an previous error that prevents return false; to be readed
2 - You can press F12 in most of browsers to open developer tools, in this case the Network Panel is what you need: Just try your code with this panel opened and see what happens there... 404 error code means "I cant find send.php!".
This FIDDLE gets a 404 because http://fiddle.jshell.net/send.php doesn't exists.
Try This works for you.
<html>
<body>
<form method="post" class="mailform" onsubmit="return false;">
<input type="submit" value="submit"/>
</form>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).on('submit','form',function()
{
var foo = '<p>Some message</p>';
$.ajax({
url: 'send.php',
type: 'post',
data: {'foo' : foo},
success: function() {
alert('email sent!');
}
});
return false;
});
</script>
</body>
</html>
Related
I am trying to send form data and js array to mysql database. I am having problem with receiving js array into my php. I receive data from form but not the array. I can't find the problem.
index.php
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"><!--bootstrap-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script><!--jquery-->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><!--angular js-->
<script type="text/javascript" src="assets/js/main.js"></script>
</head>
<body>
<form method="post" action="upload.php">
<!--dynamic form created from javascript-->
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
</body>
</html>
javascript -- main.js
var objArray = []; //Array of questions
function upload(){
var jsonArray = JSON.stringify(objArray);
$.ajax({
type:'post',
url: 'upload.php',
data: { jsonData : jsonArray},
success: function(data){
console.log("success!");
}
});
} else {
console.log("no data javascript!");
}
}
upload.php
<?php
if(($_SERVER['REQUEST_METHOD'] == "POST") && (isset($_POST['submit']))){
$servername = "......";
$username = "......";
$password = "......";
$dbname = ".....";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(!empty($_POST['jsonData'])){
$json = $_POST['jsonData'];
var_dump(json_decode($json, true));
echo "<script type=\"text/javascript\">
console.log('received data');
</script>";
} else {
echo "data not received";
}
$conn->close();
}else {echo "unsecure connection";}
?>
objArray looks like this:
[{"questionId":1,"questionTypeObj":"single","options":3},{"questionId":2,"questionTypeObj":"single","options":3}]
upload.php outputs "data not received"
Your output indicates what the problem is: You get to the part where you echo data not received but you are not sending a submit key: $_POST['submit'] is not set when called through ajax.
So you are submitting your form the "normal" way and not through ajax.
This is caused by the fact that you are not cancelling the default submit action of your button.
The best way to solve that (in my opinion...), is to remove the inline javascript - the click handler - and replace your function with:
$("form").on('submit', function(e) {
// Cancel the default form submit
e.preventDefault();
// The rest of your function
var jsonArray = JSON.stringify(objArray);
...
});
Note that I am catching the form submit event. You could also replace that with the button click event but that might not work correctly when a visitor uses the enter key in a form field.
You shouldn't be doing it this way. There's no way to guarantee that the javascript will execute before you redirect. In fact, it won't run fast enough, and will just redirect to the next page. Try
<form method="post" action="upload();">
This will get the data to the page, but it won't display it. If you want it displayed you should have forms submitting it. If you post with ajax you can also try to catch the response with jquery.
when you click the button your code are going to send 2 requests to the server
First request-the ajax
this ajax request has the parameter you need jsonData : jsonArray
and right after that you are going to send another request
Second request-submitting the form
and the form has no jsonData : jsonArray paramter sent with it
you don't need this ajax at all!
all you need to do to receive the jsonData : jsonArray paramter is to send it along with the form
for example:
change your form to be like this
<form method="post" action="upload.php">
<input id="jsonData" type="hidden" name="jsonData" value="">
<input id="submit" type="submit" value="Upload" name="submit" onclick="upload()"/>
</form>
and change your button function to be like this
function upload(){
var jsonArray = JSON.stringify(objArray);
$('input#jsonData')[0].value=jsonArray ;
}
EDIT :
Or if you want upload.php to process the ajax request, and not to response with a whole document then you don't need the form, remove the form from your HTML , and just add submit:Upload to the ajax request
data: { jsonData : jsonArray, submit:"Upload" }
I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
I have contact form on my site. It sends message to email. I try to do it without page reload using AJAX, but it seems that AJAX doesn't work: messages are sent but the page still redirecting to call-form.php. What is incorrect in my code? (jQuery is included)
HTML
<form name="freeCall" action="<?php bloginfo(template_url); ?>/mail/call-form.php" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
</form>
PHP - call-form.php
<?
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
}
?>
JS
$(function () {
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
});
Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).
Then, when submitting a form with AJAX, the tag action="" is not needed.
Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault() with the event called e here, like in my example.
I have improved your code to be more realistic about the latest standards.
HTML :
<form name="freeCall" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
JS :
$(function () {
$("#free-call-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
dataType: "json", // Add datatype
data: form_data
}).done(function (data) {
console.log(data);
alert("It's OK!");
}).fail(function (data) {
console.log(data);
});
});
});
And PHP :
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
With echo json_encode, you know what is the return of your AJAX call. It is better
You're not preventing the default submit action -
$("#free-call-form").submit(function (event) { // capture the event
event.preventDefault(); // prevent the event's default action
Returning false or preventing the default behavior of the event should work for you.
Example with old .submit(), that now is an alias of .on('eventName'); and using return false to avoid form submission.;
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
return false;
});
Example using .on('eventName') and using e.preventDefault() to avoid form submission.
$("#free-call-form").on('submit', function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
From Jquery .submit() Documentation: This method is a shortcut for
.on( "submit", handler ) in the first variation, > and .trigger(
"submit" ) in the third.
Also, you would consider not using EVER the user input directly, it would not cause problems in this exact context (or maybe yes) but with your actual approach they can change the mail markup or adding some weirds things there, even scripts, you would consider escape, validate or limit it.
Also as zLen pointed out in the comments:
the action in the form markup is not necessary because you are not using it, you can remove it:
action="<?php bloginfo(template_url); ?>/mail/call-form.php"
What is happening is your form is being submitted, it's not actually the AJAX call which is doing it. To fix it, add
return false;
at the end of the submit function so that the browser doesn't submit the form and the AJAX call happens properly.
I have a simple form with 2 input:
<form name="contact" id="contact">
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
On submit I want using jQuery ajax method to send data to print.php. Code looks next:
var contact=$("#contact");
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
I want that Print.php script simply prints sent data, but nothing is happening. Script looks next:
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
echo $fname;
?>
Problem is obviusly in print.php.
you need to use following.
$("form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "print.php",
dataType: "json",
data: {
fname: firstName,
lname: lastName
},
success: functon(dt) {
alert(dt);
}
});
});
There is no $subject variable anywhere.
You set the first name and last name variables properly.
To check your script's response (which will be an error), go to your console and check network, and then repsonse data.
Change $subject to $fname and it should "work"
Also add on .on() submit event handler to your jQuery AJAX call like so:
$('form').on('submit', function() {
//ajax call
});
Edit:
You made an edit and changed $subject to $name. There is no $name variable either.
You do not need the JSON type on the ajax form. And include the preventDefault to avoid natural action(page refreshes when submitting)
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
event.preventDefault();
$.ajax({
type:"POST",
url:"print.php",
data:{
fname:firstName,
lname:lastName
}
});
});
It looks like your problem is that your HTML form doesn't know where to go ounce the submit happens and that is why nothing is happening. You need to tell your HTML form to run javascript.
You could link your HTML form to your javascript by using JQuery's .submit() method document here http://api.jquery.com/submit/
This will trigger your javascript to run once it is submitted if you wrap all your javascript around it.
$("form").submit(function( event ) {
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
Also you could give your HTML form an action so it knows what to do when the form is submitted.
Below we are saying run myFunction() when this form is submitted, we will then need to wrap all your javascript in myFunction().
<form name="contact" action=“javascript:myFunction();”>
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
Your javascript will look like this
function myFunction(){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
}
Once you get that far you will want to fix your php. The way you have it now $name is empty and won't print anything. You will want to fill the variable in before you echo it out. I am assuming you want $name to contain a concatenated version of $fname and $lname.
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
$name = $fname . ' ' . $lname;
echo $name;
?>
That should work for you.
I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code. What I am trying to do is allow users to delete something that they posted on my site without doing a page refresh. The form is going to be passed to a php file that will modify my MySQL DB. I am new to ajax and have only messed around with PHP for a short time as well.
form:
<form class='status_feedback' id='delete_status' onsubmit='delete_status()' action=''>
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='submit' value='X'/>
</form>
delete_status()
function delete_status(){
$.ajax({
type: "POST",
url: "/scripts/home/php/delete_status.php/",
data: status_id,
success: function() {
//display message back to user here
}
});
return false;
}
delete_status.php
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status_id = $_POST['status_id'];
mysqli_query($con,"UPDATE status SET visibility = 'hidden' WHERE id = $status_id");
?>
at this point, all that happens when I strike the delete_status() function is my page refreshes and adds ?status_id=194 (when I click on status #194) to the end or my url.
Any help would be awesome. I have been researching for several days.
Change your HTML, Ajax and php a little.
HTML
Add this code:
<body>
<form class='status_feedback' id='delete_status' >
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='button' id='x_submit' value='X' />
</form>
<script>
$('#x_submit').on("click",function(){
var status_id= $('#status_id').val();
//Delete the alert message if you want.
alert("Check your status id :"+status_id);
$.ajax({
type: "GET",
url: "/scripts/home/php/delete_status.php?",
data: {status_id:status_id},
dataType:'JSON',
success: function(json) {
//display message back to user here
alert(json[0].response);
}
});
});
</script>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json');
$con=mysql_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$status_id = $_GET['status_id'];
$result = mysql_query("UPDATE status SET visibility = 'hidden'
WHERE id = '$status_id'");
if(! $result )
{
$data[]=array('response'=>"Unable to insert!");
}
else
{
$data[]=array('response'=>"Data successfully inserted into the database!");
}
$json_encode = json_encode($data);
print("$json_encode");
?>
Hope it will work.
You are not cancelling the form submission
onsubmit='delete_status()'
needs to be
onsubmit='return delete_status()'
and data: status_id, looks wrong unless you have a variable defined somewhere else