Using SweetAlert to Display messages after inserting data to MySql using php - php

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){
}
});

Related

Ajax datatable Update with PHP MySql

I want to update data using Ajax and below is the sample code. The SweetAlert get displaced that it has been updated but it doesn't take effect in the database non thus it gives an error.
Ajax Code
This is the Ajax Script for the form submission when the submit button is clicked.
<script>
$('#submit').on('click', function(event){
event.preventDefault();
var firstname = $('#firstname').val();
var othername = $('#othername').val();
var gender = $('#gender').val();
var id_type = $('#id_type').val();
var id_number = $('#id_number').val();
var issue_date = $('#issue_date').val();
var business_place = $('#business_place').val();
var food_type = $('#food_type').val();
var screened = $('#screened').val();
var sub_metro = $('#sub_metro').val();
var telephone = $('#telephone').val();
var get_date = $('#get_date').val();
var chit_number = $('#chit_number').val();
var remarks = $('#remarks').val();
var user_id = $('#user_id').val();
var vendor_id = $('#vendor_id').val();
if (firstname!="" &&othername!="" && food_type!=""){
$.ajax({
url: "action/vendor_update.php",
type: "POST",
data: {
firstname:firstname, othername:othername, gender:gender,
id_type:id_type, id_number:id_number, issue_date:issue_date,
business_place:business_place, food_type:food_type, screened:screened,
sub_metro:sub_metro, telephone:telephone, get_date:get_date,
chit_number:chit_number, remarks:remarks, user_id:user_id, vendor_id:vendor_id,
},
cache: false,
success: function(data){
if(data.statusCode=200){
$('#dataForm').find('input:text').val('');
alert('Updated');
})
}
else if (data.statusCode=201)
{
alert('Cannot Update');
}
}
});
}else{
alert('All fields are mandatory');
}
});
PHP Code ---> action/vendor_update.php
This code is for the php server side for data insertion into the database.
<?
session_start();
// include('../includes/session.php');
include('./includes/connection.php');
$query = $dbh->$prepare("UPDATE vendors SET Firstname=:firstname, Othername=:othername, Telephone=:telephone, Gender=:gender, IdType=:id_type, IdNumber=:id_number, IdDate=:issue_date, BusinessPlace=:business_place, FoodType=:food_type, Notes=:remarks, ScreenStatus=:screened, ChitNumber=:chit_number, UpdatedBy=:user_id WHERE VendorId=:vendor_id");
$query->execute([
$firstname = $_POST['firstname'];
$othername = $_POST['othername'];
$telephone = $_POST['telephone'];
$gender = $_POST['gender'];
$id_type = $_POST['id_type'];
$id_number = $_POST['id_number'];
$issue_date = $_POST['issue_date'];
$business_place = $_POST['business_place'];
$food_type = $_POST['food_type'];
$remarks = $_POST['remarks'];
$screened = $_POST['screened'];
$chit_number = $_POST['chit_number'];
$user_id = $_POST['user_id'];
$vendor_id = $_POST['vendor_id'];
]);
// $query->execute($_POST);
if ($query->execute()){
echo json_encode(array("statusCode"=>200));
} else {
echo json_encode(array("statusCode"=>500));
}
?>
Here's the cleaned up PHP code:
<?php
// Tip:
// * Use named placeholders
// * Define the query string inside prepare() so you can't "miss" and run
// the wrong query by accident
// * Use single quotes so you can't interpolate variables by accident
// and create ugly SQL injection bugs
$query = $dbh->prepare('UPDATE vendors SET Firstname=:firstname, Othername=:othername, Telephone=:telephone, Gender=:gender, IdType=:id_type...');
// Use ONE of:
// A) if you have slight differences
$query->execute([
'firstname' => $_POST['firstname'],
'othername' => $_POST['othername'],
'telephone' => $_POST['telephone'],
...
]);
// OR
// B) if you're confident the placeholders match 100% and no clean-up
// such as trim() is necessary.
$query->execute($_POST);
if ($query->execute()) {
echo json_encode(array("statusCode"=>200));
} else {
echo json_encode(array("statusCode"=>500));
}
?>
Note: It's worth noting that code like this does not need to exist, that any decent ORM will make this trivial to do. It's worth exploring what options you have there as this could be so much easier.

File attachment with AJAX and PHP

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";
}
?>

How to get php Json array data of Jquery ajax

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);

php file not called from ajax call

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?

AJAX: am I inserting data correctly?

I read many of the similar threads here to see what I'm doing wrong, but my AJAX call seems correct. What am I missing here? No alert is popping up, so I assume it's the JS side.
$("#SignupSubmit").click(function()
{
var fName = $("#txtSignFName").val();
var lName = $("#txtSignLName").val();
var email = $("#txtSignEmail").val();
var pw = $("#txtPW").val();
if( fName == "" || lName == "" || email == "" || pw == "" )
{
alert();
}
else
{
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
fName:fName,
lName:lName,
email:email,
pw:pw
},
success: function(response) {
alert(response);
}
});
}
});
And the PHP (is this correct?):
<?php
require "../connectionPages/localConnect.php";
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$email = $_POST["email"];
$pw = $_POST["pw"];
if($fName == null || $lName == null || $email == null || $pw == null)
$message = "missing required data";
else
{
$SQL = "INSERT INTO `customer/User` (custFName,
custLName,
custEmail,
custPassword)
VALUES ('$fName', '$lName','$email', '$pw')";
$mysqli->query($SQL);
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$SQL = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
$res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
json_encode($res);
}
else {
$message = "Unable to insert record: " . $mysqli->error;
}
$mysqli->close();
}
First phase update the below code in the data part.
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
And you are trying to get last inserted id. is it? if so use
$mysqli->insert_id;
instead of select query
Do this in AJAX
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
success: function(response) {
var res=eval(response);
alert(res.id);
}
});
And in your PHP page. Do this:
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$lastid = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
// $res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
echo json_encode(array('id'=>$lastid));
}
I hope it helps

Categories