Generate message after sending iFrame Email - javascript

I have used the following guide to ifugre out how to send emails with file uploading without refreshing the page: http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ and it works fine, except that I'd like to be able to take a message from the php I use to upload the file and send the email, so that I can display that message to the user, on the page where they submitted the form from.
I have this code currently in my contact.php page:
if (!$sentMail) {
header('HTTP/1.1 500 Couldnot send mail! Sorry..');
exit();
} else {
echo '<h3>Hi ' . $postName . ', Thank you for your email</h3>
<p>Your email has already arrived in our Inbox, all We need to do is Check it.
<br />Good day.</p>';
}
The only problem is getting that message that I've echoed to show up where I'd like it to go. Any help would be greatly appreciated.

The PHP in the iFrame should post unique sessionID in the database with result.
In the meanwhile you can do an Ajax call to check the database if the mail is sent.
So we got 3 files
Your form (like index.html)
Your Mailer in iframe (like sendMail.php)
Your status checker (like getStatus.php)
Here we go..
Your IFRAME Mailer:
<?php
session_start();
$_SESSION['mailsender'] = mt_rand();
// this is ur iframe mailer
// here your mail send stuff .....
// if mail is sent
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'successfull')");
// if mail fails
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'failed')");
?>
getStatus.PHP :
<?php
session_start();
// check status and give JSON back
// getStatus.php - we be called from front-end
$query = mysql_query("SELECT * FROM mailsender WHERE mailid = '".$_SESSION['mailsender']."'");
$result = "Pending";
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_array($query)) {
$result = $rij['result'];
}
}
echo json_encode(array("result"=>$result));
?>
Your Front-end like Index.html:
<!DOCTYPE html>
<html>
<!-- include jQuery -->
<script>
$(document).ready(function(){
checkMailStatus = function() {
$.ajax({
url: 'getStatus.php',
dataType: 'JSON',
success: function(data) {
if (data['result'] == "successfull") {
// do successfull stuff here
// also clear the interval
}
if (data['result'] == "failed") {
// do failed stuff here
}
if (data['result'] == "pending") {
// still trying to send
// do stuff here while sending (like loading.gif)
}
}
})
}
$(".sendmailbutton").click(function(){
setInterval(function(){
checkMailStatus();
}, 800)
})
})
</script>
</html>

Related

Server errors displayed instead of loading data from database

I don't know what I'm missing. I'm trying to load data from database into the navbar. Navbar should have different links for administrators, signed users and other users. Since I didn't make page for sign in and sign up yet, I assumed that the code from page showMenu.php called with AJAX will take last function loaded from functions.php which is a query for not signed in users. But instead of getting data back from the database to write with JS, the code fall into error property of AJAX call and in addition to that displays server error 500 for showMenu.php page. I checked all the paths for both main.js and php pages and names of tables and columns in database and everything is correct. And just for the record, connection.php includes fetch mode, so columns of tables can be accessed with ->. What do I'm missing.
js code
getViaAjax("showMenu",showMenu);
function getViaAjax(fileName, specificFunction) {
$.ajax({
url: "models/" + fileName + ".php",
method: "get",
dataType: "json",
success: function(jsonData){
specificFunction(jsonData);
},
error: function(xhr){
console.error(xhr);
}
});
}
function showMenu(menuJsonData){
let writingMenu = "";
menuJsonData.forEach(partOfMenu=>{
writingMenu+=`<li id="${partOfMenu.id}" class="nav-item">
<a class="nav-link" href="${partOfMenu.href}">${partOfMenu.label}</a>
</li>`;
});
document.getElementById("menu").innerHTML=writingMenu;
}
showMenu.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
include "../config/connection.php";
include "functions.php";
try{
if(isset($_SESSION['user'])){
$user = $_SESSION['user'];
if($user->roleId==1){
$jsonMenu = showMenuForAdmin();
}
else {
$jsonMenu = showMenuForSignedInUser();
}
}
else{
$jsonMenu = showMenuForNonSignedInUser();
}
echo json_encode($jsonMenu);
http_response_code(200);
}
catch(PDOException $exception){
http_response_code(500);
}
}
else{
http_response_code(404);
}
?>
function from functions.php I want to be triggered when user not registered or signed
function showMenuForNonSignedInUser(){
global $connection;
$query = "SELECT id, href, label WHERE id NOT LIKE 6;";
$data = $connection->query($query)->fetchAll();
return $data;
}

Cannot Redirect when Logging in an Account using javascript and php

Currently, I am developing a website, for my own purposes. I am a beginner at web developing so please understand me if I am not getting this correct. Please Help.
I have a code for javascript when clicking an html element button
for logging in. see code below:
$(document).ready(function(){
$("#login").click(function(){
var username = document.getElementById("username").value;
var pword = document.getElementById("password").value;
validateUser(username,pword);
});
});
function validateUser(user,pass){
var username =user;
var pword =pass;
var datasend = "username="+ username + "&password=" + pword;
$.ajax({
type:'POST',
url:'../bench/php/login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
alert("Hello World"); //Trying to pop up
$('#username').val('');
$('#pword').val('');
}
});
}
I successfully triggered the button for the second time I try to click it, and the hello world message will pop out, but it cannot redirect the page if it was successfully logged in using an account in MySQL in WAMP server. Here is the code in PHP below:
<?php
// require("php/config.php");
include("config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("Location: index.html");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");';
echo '}, 100);</script>';
}
}
?>
The problem is, the page does not redirect to the index.html even when the second click triggers the HELLO WORLD alert.
I don't know what I am doing wrong.
I don't why this is not working, I see the console, there is no error exist.
can someone help me with this? any help will much be appreciated. thanks and regards.
If you'd like to keep to using the AJAX setup you have at the moment (which is totally fine), what you'll need to do is to beef up the on-success function to read the returned results from your PHP.
A simple example
Instead of
header("Location: index.html");
write
echo "index.html";
exit;
and then add the following to your on-success function:
window.location.href = msg;
That will start to give you a flavour of how the relationship between an AJAX call and your PHP server should look like.
Next steps
Instead of having your AJAX return a string (index.html) have it
return an array of information, perhaps you want to welcome the user
with a personalised message?
You don't need to create a string (var datasend = "username="+ username + "&password=" + pword;) and feed that to your AJAX call, you can send an array.
Make sure your passwords are not stored in plain text on the server.
An ajax request will not follow the Location header of responses to redirect users.
You need to either redirect the user manually using JS in the success callback or change your form submission to use a classic HTML form
The first thing to make sure, PHP Redirect Header doesn't work when sending an Ajax Request.
So the solution to your problem is:
Change this part of your code in PHP file:
header("Location: index.html");
Into:
echo "Success";
exit();
And then in your Ajax Request Success Callback:
success:function(msg){
if (msg == 'Success') {
window.location = "/path/to/redirect";
}
}
Let me know if you have still confusion in this.

SQL query not being executed from AJAX '$_POST' to PHP file

I'm retrieving user information from the facebook API and sending it via AJAX to my php file to write into the mysql database.
The reason for this is so I can generate a random voucher code to give to them, which is also being written to the database.
I'm not at all experience in this and I'm just learning along the way.
my php file:
<?php
include_once 'db_connect.php';//$mysqli = new mysqli(HOST, USER, PASSWORD,
DATABASE);
include_once 'psl-config.php';//database login details
if(isset($_POST['name'],$_POST['email'],$_POST['id'])){
$name = $_POST['name'];
$email = $_POST['email'];
$uid = $_POST['id'];
$code = generateRandomString();
$prep_stmt="INSERT INTO memberinfo (name, email, id,code,dateadded) VALUES ('$name','$email','$uid','$code',now())";
$stmt = $mysqli->prepare($prep_stmt);
if($stmt) {
$stmt->execute();
$stmt->close();
}}
my javascript then runs this from the facebook button with the onlogin="checkLoginState();" function:
function checkLoginState() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me', { locale: 'en_US', fields: 'name,email,id' },
function(response) {
$.ajax({
method: "POST",
url: "includes/process_fb_login.php",
data: response,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
}
});
});
}else{
alert("Failed to login");
}
});
}
At the moment nothing is being written into the database and I'm not even sure how to troubleshoot to see what's being executed along the way.
I had a couple of issues:
Firstly - My database id was type "Integer". Meaning the ID number I was getting from facebook was 15 characters long and the maximum value you can have is 2147483647(10 chars) (Signed) or 4294967295 (Unsigned). So I changed this to varchar.
Secondly - It seems that if(isset($_POST['name'],$_POST['email'],$_POST['id'])) was stuffing me up a bit, I couldn't get it to run past that line.
In the end this is the code that worked for me.
Not sure if it's the best way to do it but, hey, it works for me.
$email_exists="select email from memberinfo where email ='".$_POST['email']."'";
$exe = $mysqli->prepare($email_exists);
if($exe) {
$exe->execute();
$exe->store_result();
if ($exe->num_rows == 1) {
// A user with this email address already exists
$exe->close();
} else {
$prep_stmt = "INSERT INTO memberinfo (name, email,username,id,code,dateAdded)
VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['email']."','".$_POST['id']."','$code',now())";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->execute();
$stmt->close();
}
}}

Data Not inserting to DB - PHP MYSQL

Trying to get together the sign up validation with PHP and Ajax. Not sure what is wrong but the submission does not happen. If I don't add the validation part everything looks fine and i am able to insert the data to mysql.
<script type="application/javascript">
$("#submit").submit(function (event) {
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signupregister.php",
type: "POST",
data: datatopost,
success: function (data) {
if (data) {
$("#signupmessage".html(data));
}
},
error: function () {
$("#signupmessage").html("<div class = 'alert alert-danger'></div>")
}
});
});
</script>
_
<?php
session_start();
include('mysqlconnection.php');
include('index.php');
function customError($errors, $errorslevel)
{
}
set_error_handler("customError", E_ALL);
if (isset($_POST['submit'])) {
if ($_POST($first_name) == "") {
$errors .= $first_nameError;
} else {
$first_name =
filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
}
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' .
$errors . '</div>';
echo $resultMessage;
exit;
}
$first_nameError = '<p>first name required</p>';
First up, in your validation PHP script, you won't need to include 'index.php'
Try redirecting the form to an empty page where you only include your validation data, while setting a session variable for the first error encountered.
At the end of your validation, if your error variable contains an error, you can redirect to the form and display your said error at a convenient location. Keep in mind you will have to save form data in session variables if you want to preserve all user input (thus removing the hassle of refilling the form over and over again).
If it doesn't, you can proceed to insert the data in your db then redirect to your desired landing page.
Here's a sample code based on your input:
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//so on for your other variables
if($_SESSION['fname'] == ""){
$_SESSION['err'] = "First Name Required";
}
if(//insert your format validation for first name){
$_SESSION['err'] = "First Name Invalid";}
}
//end of validation
if isset($_SESSION['err']){
header('Location: myform.php');
}
else{
//save all your variables into normal ones, i.e $fname-$_POST['fname'];
//insert into database;
//check correct insertion;
//redirect to landing page;
}
}
?>

from PHP to Javascript to enter PHP again and set Sessions

Im trying to fix this issue im having. The problem is that I use this code when someone want to sign in to the admin panel:
<script>
function myFunction() {
//alert('you can type now, end with enter');
$("#test").focus();
}
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
// alert($("#test").val());
var email = $("#test").val();
if(email==''){
// alert("Error.");
sweetAlert("Oops...", "Error!", "error");
} else {
$.post("sess.php",{ code1: code},
function(data) {
// alert(data);
// swal(data);
if((data)=="1") {
swal("Welcome!", "Please wait!", "success")
} else {
sweetAlert("Oops...", "Something went wrong.", "error");
}
$('#form')[0].reset(); //To reset form fields
});
}
});
});
</script>
Sess.php looks like this:
<?php
include("conn.php");
?>
<?php
include("ipcheck.php");
$code2=htmlEntities($_POST['code1'], ENT_QUOTES);
$info = explode("-", $code2);
$username = $info[0];
$password = $info[1];
$_POST = db_escape($_POST);
$sql = "SELECT id FROM adminusers
WHERE user='{$username}'
AND pass='$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0){
echo "2";
exit;
}
// Session for user
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
// DAtabse going on here.
echo "1";
exit;
?>
So if the username and password is correct the login is successful and those session is set in sess.php:
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
My problem is, how do I get the sessions that is set for the user thru sess.php back to index.php using javascript so I can set the sessions in index.php not in sess.php?
why to you care to pass the session to javascript ? I mean if you set the session server side on sess.php you have already setted it even in index.php (session exists during the entire ... session :-) ) so when sess.php return that the authentication is correct, your javascript should just move the page to index.php like:
window.location.href = 'index.php';
in index.php, if you print the session print_r($_SESSION) you should see the values that you have previously set in sess.php
If your $_SESSION is empty in index.php probably you have to start the session before reading $_SESSION using session_start();

Categories