Have a problem to call my server.php to add some values into db.
server.php:
<?php
$db = new PDO('mysql:host=localhost;dbname=test','user','password');
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$stmt = $db->prepare("INSERT INTO user (name,email,phone,address) VALUES(?,?,?,?)");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$email);
$stmt->bindParam(3,$phone);
$stmt->bindParam(4,$address);
$stmt->execute();
echo "data saved";
?>
Calling the server.php directly, the data will be saved.
But from my Html/Ajax code it will not:
<script>
function saveData(){
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "server.php",
data: "name=" +name+"&email="+email+"&phone="+phone+"&address="+address,
}).done(function(data){
alert('success');
$('#result').html("<br/><div> class='alert alert-info'>" + data +"</div>");
)};
return false;
</script>
The alert('success') won't be called also #result div isn't filled.
Whats wrong with this code?
Related
I want to add file upload function to my job application form. For now everything is working, i get a meesage to my mail but i want to add CV upload option. I made input type file for that but i dont know how to take that file and send it to my mail as attachment. Thank u.
This is my AJAX code:
var sucessMessagee = $("#sucessMessage");
$("#contact_form").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
console.log('Invalid form');
} else {
event.preventDefault();
submitForm();
}
});
function submitForm(){
var name = $("#name").val();
var surname = $('#surname').val();
var email = $("#email").val();
var year = $("#year").val();
var month = $("#month").val();
var day = $("#day").val();
var adress = $("#adress").val();
var phone = $("#phone").val();
$.ajax({
type: "POST",
url: "/php/jobs.php",
data: "name=" + name + "&surname=" + surname + "&email=" + email + "&year=" + year + "&month=" + month + "&day=" + day + "&adres=" + adress + "&phone=" + phone,
success : function(text){
if (text == "success"){
formSuccess();
} else {
console.log('Failed message');
}
}
});
};
function formSuccess(){
$("#contact_form")[0].reset();
$("#posao1").css("display", "none");
showMessage();
setTimeout(function() {sucessMessagee.css('display', 'none')},4000);
};
function showMessage() {
sucessMessagee.css('display', 'block');
};
And this is my php code:
<?php
require 'phpmailer/PHPMailerAutoload.php';
$result = $_POST['result'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$adress = $_POST['adress'];
$phone = $_POST['phone'];
/*if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != "") {
$file = "attachment/" . basename($_FILES['attachment']['name']);
move_uploaded_file($_FILES['attachment']['tmp_name'], $file);
} else
$file = "";*/
$mail = new PHPMailer;
$mail->setFrom($email, 'Prijava za posao');
$mail->addAddress('luka9825#hotmail.com', 'Office');
$mail->Subject = 'Prijava za posao sa sajta proenterijer.rs';
$mail->Body = "Ime i prezime: $name $surname
\nDatum rođenja: $day.$month.$year
\nAdresa stanovanja: $adress
\nKontakt telefon: $phone
\nE-Mail adresa: $email";
if(!$mail->send()) {
} else {
echo "success";
}
?>
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data + "name=" + name + "&surname=" + surname + "&email=" + email + "&year=" + year + "&month=" + month + "&day=" + day + "&adres=" + adress + "&phone=" + phone,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
Now you can get the file from $_GET['files'] in php and then use that to send through the email. Add
You will have to need a slight modification to your submitForm() function as follows:
function submitForm(){
var name = $("#name").val();
var surname = $('#surname').val();
var email = $("#email").val();
var year = $("#year").val();
var month = $("#month").val();
var day = $("#day").val();
var adress = $("#adress").val();
var phone = $("#phone").val();
var form_data = new FormData();
form_data.append('file', $('#ID_OF_YOUR_FILE_INPUT').prop('files')[0]);
form_data.append('name',name);
form_data.append('surname',surname);
form_data.append('email',email);
form_data.append('year',year);
form_data.append('month',month);
form_data.append('day',day);
form_data.append('adress',adress);
form_data.append('phone',phone);
$.ajax({
type: "POST",
url: "/php/jobs.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success : function(text){
if (text == "success"){
formSuccess();
} else {
console.log('Failed message');
}
}
});
};
And your PHP would have to be modified to something like:
<?php
require 'phpmailer/PHPMailerAutoload.php';
$result = $_POST['result'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$adress = $_POST['adress'];
$phone = $_POST['phone'];
$mail_attachment = $_FILES['file']; // Observe, you don't have to upload the file to your server
$mail = new PHPMailer;
$mail->setFrom($email, 'Prijava za posao');
$mail->addAddress('luka9825#hotmail.com', 'Office');
$mail->addAttachment($mail_attachment);
$mail->Subject = 'Prijava za posao sa sajta proenterijer.rs';
$mail->Body = "Ime i prezime: $name $surname
\nDatum rođenja: $day.$month.$year
\nAdresa stanovanja: $adress
\nKontakt telefon: $phone
\nE-Mail adresa: $email";
if(!$mail->send()) {
} else {
echo "success";
}
?>
My jQuery Ajax code:
$(".comment").click(function(){
var id = $(this).data("id");
var name = $("#username_"+id).val();
if(name==''){
alert("Please Fill All Fields");
}else{
$.ajax({
type: "POST",
url: "comments",
data:{username:name},
dataType: "JSON",
success: function(jsonStr){
$("#cmt_output").html(JSON.stringify(jsonStr));
}
});
}
});
My Php Code:
............
$con = mysqli_connect("localhost","root","","quotes") or die("Error".mysqli_error($con));
$name = $_POST['username'];
$user = get_userdetails();
$vw_id = $user->id;
$query = mysqli_query($con,"INSERT INTO tlb_comments(user_id,comments) values ('$vw_id','$name')");
$comments = mysqli_query($con,"SELECT * FROM tlb_comments");
$avatar = mysqli_query($con,"SELECT * FROM tlb_avatar WHERE `vw_id`='".$vw_id."'");
$avatar_select = mysqli_fetch_all($avatar);
$comment_select = mysqli_fetch_all($comments);
array_push($avatar_select,$comment_select);
echo json_encode($avatar_select);
I have combined html, php and ajax to insert data in mysql database. And I want to display success or error messages in ajax success function using SweetAlert. The data is getting inserted into the database but I am unable to display the messages.
Following is my code:
insert.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("hotelmanagement", $connection);
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$checkInDate = $_POST['checkInDate'];
$checkOutDate = $_POST['checkOutDate'];
$adults = $_POST['adults'];
$children = $_POST['children'];
$specialInstructions = $_POST['specialInstructions'];
$query = mysql_query("INSERT INTO reservation(FirstName,LastName,Address1,Address2,Phone,Email,Adults,Children,CheckInDate,CheckOutDate,SpecialInstructions) VALUES('$fName','$lName','$address1','$address2','$phone','$email','$checkInDate','$checkOutDate','$adults','$children','$specialInstructions')");
echo json_encode($query);
mysql_close($connection);
?>
And this is my ajax code:
$("#submit").click(function(){
var fName = $("#fName").val();
var lName = $("#lName").val();
var address1 = $("#address1").val();
var address2 = $("#address2").val();
var phone = $("#phone").val();
var email = $("#email").val();
var checkInDate = $("#checkinDate").val();
var checkOutDate = $("#checkoutDate").val();
var adults = $("#adults").val();
var children = $("#children").val();
var specialInstructions = $("#specialInstructions").val();
if(fName == '' || lName == '' || phone == ''){
swal("Oops!!", "Looks like you missed some fields. Please check and try again!", "error");
}else{
$.ajax({
type:'post',
url:'insert.php',
data: {fName:fName,lName:lName,address1:address1,address2:address2,phone:phone,email:email,checkInDate:checkInDate,checkOutDate:checkOutDate,adults:adults,children:children,specialInstructions:specialInstructions},
dataType:'json',
succcess:function(data){
swal("Success", "Data Saved Successfully", "success");
},
error:function(xhr, thrownError, ajaxOptions){
},
});
}
});
Could you please tell me what am I missing. Thank you.
your success callback is triple ccc and try to remove dataType:'json',
try this ajax request
$.ajax({
type:'post',
url:'insert.php',
data: {fName:fName,lName:lName,address1:address1,address2:address2,phone:phone,email:email,checkInDate:checkInDate,checkOutDate:checkOutDate,adults:adults,children:children,specialInstructions:specialInstructions},
success:function(data){
swal("Success", "Data Saved Successfully", "success");
},
error:function(xhr, thrownError, ajaxOptions){
}
});
I'm having a perplexing problem--I'm managing to get one value, extracted from a text box, successfully inserted into my table but the other (also from a text box) is not going in. Before the AJAX call, I've alerted my datastring to make sure both values are correct, and they are. When I look in the database, however, only the name value is entered and email is blank.
HTML:
<div id="basic-modal-content">
<h3>Please Alert me when this is Available</h3>
<p>Your Name: <input type="text" id="alert_name"/></p>
<p>Email Address: <input type="text" id="alert_email"/></p>
<button id="alert_submit">Submit</button>
</div>
Javascript:
$('#alert_submit').click(function(){
var datastring = 'name='+ $('#alert_name').val() + '&email=' + $('#alert_email').val();
alert(datastring);
$.ajax({
type: "POST",
url: "process_email.php",
data: datastring,
success: function(data) {
}
});
alert ("We've received your request and will alert you once the directory is available. Thank you.");
$.modal.close();
});
PHP:
$name = $_POST['name'];
$email = $_POST['email'];
try {
$conn = new PDO('mysql:host=blah;dbname=blah', '-', '-');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("INSERT INTO email_alerts(name, email) VALUES(':name, :email)");
$stmt->execute(array('name' => $name, 'email' => $email));
//$affected_rows = $stmt->rowCount();
$conn = null;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$conn = null;
}
try this code please
$('#alert_submit').click(function(){
$.ajax({
type: "POST",
url: "process_email.php?name="+$('#alert_name').val() +"&email="+ $('#alert_email').val(),
success: function(data) {
}
});
alert ("We've received your request and will alert you once the directory is available. Thank you.");
$.modal.close();
});
I am trying to retrieve information from my php file which contains the following code. My code contains the colums Email, FirstName, LastName, and State.
$query = 'SELECT * FROM users WHERE LOWER(Email) = :email';
$stmt = $dbh->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();
if ($stmt->rowCount() == 1) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$firstName = $row['FirstName'];
$lastName = $row['LastName'];
$state = $row['State'];
} echo json_encode($row);
My Ajax code is:
$.ajax({
datatype: 'json',
type: "POST",
url: 'json-data.php',
success: function(data) {
//called when successful
$('#firstname').append(data.FirstName);
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
When I type $('#firstname').append(data);, it shows me the following output:
{"FirstName":"Foo","LastName":"Bar","State":"Florida","Email":"foo#bar.com"}
How do I make it so I can get only the first name and append it to a div?
try with:
var obj = jQuery.parseJSON(data);
$('#firstname').append(OBJ.FirstName);