I have a javascript fucntion below
function loginsubmit() {
var url = "../php/loginsubmit.php";
var data = "";
ajaxRequest(url, "POST",data , true, insertNewBody);
}
Which then creates my ajax request to post to my php code which is
<?php
session_start();
require_once ("db.php");
$username = $_POST['username'];
$password = $_POST['password' ];
echo $username;
$query = "select * from logindetails where username='$username' and password='$password'";
$result = mysql_query($query);
if(mysql_num_rows($result) == 1) {
$row = mysql_fetch_assoc($result);
$_SESSION['logged_in'] = TRUE;
} else {
$_SESSION['logged_in'] = FALSE;
}
mysql_close();
?>
These two pieces of code below are returning a null value and i can't see why?
$username = $_POST['username'];
$password = $_POST['password'];
It's because you're actually never setting the post values username and password in your javascript.
Put data in your data variable:
function loginsubmit() {
var url = "../php/loginsubmit.php";
var data = {username: 'yourusername', password: 'yourpassword'};
ajaxRequest(url, "POST",data , true, insertNewBody);
}
As clarified by others already, you are not sending data.. here is how you should:
function loginsubmit() {
var url = "../php/loginsubmit.php";
var username = document.myLoginForm.username.value;
var password = document.myLoginForm.password.value;
ajaxRequest(url, "POST", {username: username, password: password}, true, insertNewBody);
}
replace "myLoginForm" with the actual name of your form. Also there are other ways too to retrive values from input fields such as using element IDs of those feilds.
An ajax suggestion based on what Ruben is saying, you need to pass the username and password up to PHP in your login call.
$.ajax({
url : "../php/loginsubmit.php",
type: "POST",
data : {username:"theUsernameString",password:"thePasswordString"},
success: function(data, textStatus, jqXHR)
{
//data - contains the response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
//handle the error
}
});
Related
I'm having problems figuring out what is wrong with my json. I used php's json_encode.So, on every page I have the some form which need be sent on each page to different email address. However, if I comment jQuery file, then the form is submitted correctly, all data inserted into database correctly, and in place of jQuery AJAX response I get valid JSON, like
{"response":"success","content":{"3":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Milano!"}}
If I want to read and process this data with jQuery instead of get valid response I get just empty [] I was try a lot of options and so if I add JSON_FORCE_OBJECT instead of get empty [] I get empty {}. However if I write json data which need to encode after closing tag for if (is_array($emails) && count($emails) > 0) { just then json data it's encoded correctly and when a form is submitted I get valid response, but in this case form isn't sent and data isn't inserted into db. Bellow is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$error = false;
$response = [];
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try {
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$response['response'] = 'error';
$response['errors'][] = $e->getMessage();
echo json_encode($response);
die();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit'])) {
//print_r($_POST);
$fname = $_POST['fname'];
$tel = $_POST['tel'];
if (empty($fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can not be empty!';
} else {
if (!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can contain just letters and white space!';
}
}
if (empty($tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can not be empty!";
} else {
if (!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can contain from 9 to 15 numbers!";
}
}
if (!$error) {
// Instantiate a NEW email
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret.com';
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Username = 'booking#secret.com';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->setFrom('booking#secret.com');
$mail->clearAddresses();
$mail->Subject = "New message from secret.com";
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1, $pages_id);
$dbstmt->execute();
//var_dump($dbstmt);
$emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
if (is_array($emails) && count($emails) > 0) {
foreach ($emails as $email) {
//var_dump($email['email_address']);
$mail->addAddress($email['email_address']);
$body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
$mail->Body = $body;
if ($mail->send()) {
$mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
$response['response'] = "success";
$response['content'][$email['email_address_id']] = "Thanks " . ucwords($fname) . "! Your message is successfully sent to owner of property {$email['owner_property']}!";
}//end if mail send
else {
$response['response'] = "error";
$response['content'][$email['email_address_id']] = "Something went wrong! Try again..." . $mail->ErrorInfo;
}
}//end foreach for email addresses
} //end if for array of emails
/* If use this else for response I allways get this response. Even, if I write JSON for success hier I get it but data isn't sent and isn't inserted into db
else {
$response['response'] = 'error';
$response['error'][] = '$emails is either not an array or is empty'; // jQuery just read this
}//end if else for array of emails
*/
}//end if validation
}//end submit
echo json_encode($response);
}//end REQUEST METHOD = POST
And this is jQuery for submitHanfdler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData); //this work
jQuery.ajax({
url: '/classes/Form_process.class.php',
type: 'post',
data: formData,
dataType: 'json',
cache: false,
success: function (response) {
jQuery("#response").text(response['content']);
// debbuger;
console.log(response);
//console.log(response.hasOwnProperty('content'));
},
error: function (response) {
// alert("error");
jQuery("#responseOwner").text("An error occurred");
console.dir("Response: " + response);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
Thanks in advance for any kind of your help, any help will be highly appreciated!
I suspect the issue is the dataType: 'json' attribute. This is because the serialize function does not provide json data. See if this works:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: jQuery("#contactOwner").serialize()
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
Alternatively, if you want to use dataType: 'json', you will need to send in json data:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: {
firstName: jQuery("#contactOwner .first-name").val(),
lastName: jQuery("#contactOwner .last-name").val(),
...
}
dataType: 'json',
cache: false,
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
If you add you data using an object as shown above this should work with dataType: 'json'.
How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});
I'm trying to write a page to make a POST request to a php script and I feel like I've done it right, it's worked everywhere else so it seems but I keep getting a "unidentified error" and it won't work, how can I get this to work?
Javascript:
$(document).ready(function() {
$("#x").click(function() {
var email = $("email").val();
var pass = $("password").val();
var confirmPass = $("confirmPassword").val();
var name = $("name").val();
var question = $("question").val();
var answer = $("answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "*********";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $_POST["email"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$question = $_POST["question"];
$answer = $_POST["answer"];
$sql = "INSERT INTO accounts (accountEmail, accountPassword, accountName, accountQuestion, accountRecover) VALUES ('$email', '$pass', '$name', '$question', '$answer')";
$conn->close();
if(mysql_affected_rows() > 0) {
$response = "Account added successfully!";
}
else {
$response = "Couldn't add account!";
}
$pre = array("Response" => $response);
echo json_encode($pre);
?>
You need to properly use jquery.
For example
var email = $("email").val(); //IS WRONG
Should be (if you have input id="email")
var email = $("#email").val();
If you have only name you can use
var email = $("[name='email']").val();
A bit offtopic:
If you are using form ajax submit consider jquery method serialize https://api.jquery.com/serialize/ for getting all form values (or some jquery ajaxform plugin).
And please! don't make insecure mysql statements. For gods sake use prepared statements.
If you need very basic stuff just use prepared statements or consider https://phpdelusions.net/pdo/pdo_wrapper
Also a small tip: before echo json make json header
<?php
header('Content-type:application/json;charset=utf-8');
I think you are mistaken with your jquery data, they should have identifier like id denoted by '#' and classes denoted by '.', do it this is you have id="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $("#email").val();
var pass = $("#password").val();
var confirmPass = $("#confirmPassword").val();
var name = $("#name").val();
var question = $("#question").val();
var answer = $("#answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR like this is you have class="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $(".email").val();
var pass = $(".password").val();
var confirmPass = $(".confirmPassword").val();
var name = $(".name").val();
var question = $(".question").val();
var answer = $(".answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR if you want to use the name directly follow this:
$(document).ready(function() {
$("#x").click(function() {
var email = $("input[name='email']").val();
var pass = $("input[name='pasword']").val();
var confirmPass = $("input[name='confirmPassword']").val();
var name = $("input[name='name']").val();
var question = $("input[name='question']").val();
var answer = $("input[name='answer']").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
I hope this helps you
There are lots of reasons your code is not working. #AucT and #gentle have addressed your Javascript side issues so I'll focus on PHP. Your query code is:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "...";
$conn->close();
Notice that:
you never execute you query. $sql is just a string held in memory.
you're mixing mysqli function with mysql_ function (mysql_affected_rows); that won't work
You're inserting POST data directly into your queries, so you are very vulnerable to SQL injection
At the end, you echo JSON, but you haven't told the browser to expect this format
Do this instead:
$conn = new mysqli(...);
//SQL with ? in place of values is safe against SQL injection attacks
$sql = "INSERT INTO accounts (accountEmail, accountPassword,
accountName, accountQuestion, accountRecover) VALUES (?, ?, ?, ?, ?)";
$error = null;
//prepare query and bind params. save any error
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssss',$email,$pass,$name,$question,$answer)
or $error = $stmt->error;
//run query. save any error
if(!$error) $stmt->execute() or $error = $stmt->error;
//error details are in $error
if($error) $response = "Error creating new account";
else $response = "Successfully created new account";
//set content-type header to tell the browser to expect JSON
header('Content-type: application/json');
$pre = ['Response' => $response];
echo json_encode($pre);
I'm struggling to pass data using ajaxForm to my PHP file so I can insert into a MySQL database.
Below is the JavaScript function which currently displays a progress bar during form submitting, the problem is the 'post' of name, phone and email don't work but the attachment upload does.
$(function() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;
var percent = $('.percent');
var bar = $('.bar');
$('form').ajaxForm({
dataType: 'json',
data : {
name:name,
phone:phone,
email:email
},
beforeSend: function() {
document.getElementById("bar").style.backgroundColor="rgb(51,166,212)";
bar.width('0%');
percent.html('0%');
},
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
percent.html(pVel);
},
complete: function(data) {
document.getElementById("bar").style.backgroundColor="rgb(185,221,111)";
percent.html("Done!");
setTimeout(function(){
modal.style.display = 'none';
location.reload();
}, 2000);
}
});
});
Here is the code from the PHP file the values are to be passed to.
<?php
include("sql_connection.php");
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$sql = "INSERT INTO helpdesk (Name, Phone, Email) VALUES ($name, $phone, $email)";
mysqli_query( $conn, $sql);
$dir = 'uploads/';
$count = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files']))
{
foreach ( $_FILES['files']['name'] as $i => $name )
{
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $dir . $name) )
$count++;
}
}
echo json_encode(array('count' => $count));
?>
Any advice?
Thanks
Change your SQL query to:
$sql = "INSERT INTO helpdesk (Name, Phone, Email) VALUES ('".$name."', '".$phone."', '".$email."')";
otherwise you need to change your include at the top where you start your database connection.
As I read in your comment the problem is that possibly the inputs doesn't contain any value. When are you launching the Ajax request? After a submit or on page load?
Maybe you can add the code where he should take his information from?
Missing type param in $.ajax
$('form').ajaxForm({
type: 'POST',
dataType: 'json',
data : {'name':name,'phone':phone,'email':email},
......................................
All, thanks for your help, the SQL query was in fact wrong but I also needed to use a function for each variable to return its current state before posting.
Thanks
$('form').ajaxForm({
type: 'POST',
dataType: 'json',
data : {
name:function () {
return name = document.getElementById("name").value;
},
phone:function () {
return phone = document.getElementById("phone").value;
},
email:function () {
return email = document.getElementById("email").value;
}
},
I have an ajax request that looks like this
$(document).ready(function() {
$(document).on('click', '#submit', function() {
var UserName = $('#username').val();
var PassWord = $('#password').val();
console.log(UserName);
$.ajax({
type: 'POST',
url: 'ajax/Login.php',
dataType: "text",
data: {
username: UserName,
password: PassWord
},
success: function(data) {
alert(JSON.stringify(data));
window.location='pages/mainpage.php';
},
error: function(data) {
alert('Login Error');
//window.location='../index.php';
}
});
});
});
and my php is like this
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
echo "Welcome ".$username;
}else{
echo "Password incorrect";
}
}
}else{
echo "Username is empty";
}
When i dont put anything in username i am expecting that the alert will be Username is empty same as when password is empty alert should be Password incorrect but i am getting "\r\n\" but if put some in username like John it will alert Welcome John"\r\n\" why is this happening?how to make it alert Username is empty when username is empty same with password?any idea is accepted..
Try this: in ajax section, dataType: "text", change to dataType: "json", and server php code is following: it may work
//put this function top of this page
ob_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$json="";
if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
$json.="Welcome ".$username;
}else{
$json.="Password incorrect";
}
}
}else{
$json.="Username is empty";
}
ob_end_clean();
echo json_encode($json);
?>
I change isset to !empty fixed the problem