I am attempting to have the user enter their un/pw, click a button, have a javascript function take the un/pw entered, send it to a php script which will return a 1 or 0 based on whether the un/pw was valid.
In the javascript page I have:
function handleLogin() {
var username = document.getElementById('un').value;
var password = document.getElementById('pw').value;
var valid = $.post("getLogin.php", {"un": username, "pw": password}, "json");
alert(valid);
}
In the php file I have:
$username = $_POST['un'];
$password = $_['pw'];
$valid = 0;
# This section will open a connection to the existing backup server and get the last ith_rid used.
# It will then store that ith_rid to be used later and then close the database connection
$mysqlconn = new mysqli('localhost','username','password','database');
if ($mysqlconn->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqlconn->connect_errno . ") " . $mysqlconn->connect_error;
}
###################################################
## Get username and password
##################################################
$res = $mysqlconn->query("SELECT username, password FROM table WHERE username = '" .$username . "'");
if (!$res) { ##If there is an error running query, display it to the screen.
echo "Error: $mysqlconn->error \n";
}
while($row = $res->fetch_assoc()) {
$un = trim($row["username"]);
$pw = trim($row["password"]);
}
if ($un == $username && $pw == $password){
$valid = 1;
}
echo json_encode($valid);
The php does return something, but it is in an object. Not sure how to access the variable from the javascript in order to determine if it is 1 or 0.
Edit:
So I changed things up a bit and it is working correctly now.
carrierchange.js
jQuery(document).ready(function () {
$("#content").append("<form name='loginForm' autocomplete='off'>");
$("#content").append("<table align=center>");
$("#content").append("<tr><td colspan=2 bgcolor=#87C9FF><center><h2>Login</h2></center></td></tr>");
$("#content").append("<tr><td><label for='un'>Username:</label></td><td><input id='un' name='un'></td></tr>");
$("#content").append("<tr><td><label for='pw'>Password:</label></td><td><input id='pw' name='pw' type='password'></td></tr>");
$("#content").append("<tr><td colspan=2><center><input type='submit' class='btn' value='Login' onClick='handleLogin()'></center></td></tr>");
$("#content").append("</table>");
$("#content").append("</form>");
document.getElementById('un').focus().focus();
});
function handleLogin() {
var username = document.getElementById('un').value;
var password = document.getElementById('pw').value;
var valid;
$.get("getLogin.php", {un: username, pw: password}, "json", function(data) {
console.log(data);
});
}
getLogin.php
<?php
$username = $_GET['un'];
$password = $_GET['pw'];
$valid = 0;
# This section will open a connection to the existing backup server and get the last ith_rid used.
# It will then store that ith_rid to be used later and then close the database connection
$mysqlconn = new mysqli('localhost','username','password','datebase');
if ($mysqlconn->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqlconn->connect_errno . ") " . $mysqlconn->connect_error;
}
###################################################
## Get username and password
##################################################
$res = $mysqlconn->query("SELECT username, password FROM cc_user WHERE username = '" .$username . "'");
if (!$res) { ##If there is an error running query, display it to the screen.
echo "Error: $mysqlconn->error \n";
}
while($row = $res->fetch_assoc()) {
$dbusername = trim($row["username"]);
$dbpassword = trim($row["password"]);
}
if ($dbusername == $username){
$valid = 1;
}
echo json_encode($valid);
?>
Since $.post is an asynchronous request, you should handle the received data in the callback function:
$.post("getLogin.php", {"un": username, "pw": password}, "json", function(data) {
console.log(data); //received data
});
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'.
All I want to do is print 'win!' if they log in with their details in the Database (working correctly) and 'loss' if for some reason their info was not found in the DB.
So my issue is that for some reason my line of code 'echo $email;' doesn't work. It seems be set to NULL.
At the moment it only ever prints 'loss' regardless what i enter, but, if I add a row in the database that has a blank email and password (email = "", password="") then the php script returns 'win!'.
PHP CODE:
<?php
// echo "php test";
//server info
$servername = "localhost";
$username = "root";
$dbpassword = "root";
$dbname = "personal_data";
//Establish server connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
//Check connection for failure
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//Read in email & password
echo "reading in email & password...";
$email = mysqli_real_escape_string($conn, $_POST['email1']);
$password = mysqli_real_escape_string($conn, $_POST['password1']);
echo $email; //this prints blank
echo $password; //this also prints blank
$sql = "SELECT Name FROM personal_data WHERE Email='$email' AND Password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
echo "win!!";
} else {
echo "loss";
}
mysqli_close($conn);
?>
JS CODE:
$(document).ready(function(){
// alert("js working");
$('#login_button').click(function(){
var email = $('#email').val(); //prints the correct value
var password = $('#password').val(); //prints the correct value
var dataString = 'email1=' + email
+ '&password1=' + password;
$.ajax({
type: "POST",
url: "http://localhost:8888/php/login.php",
data: dataString, //posts to PHP script
success: success()
});
});//eo login_button
function success(){
alert("success");
}
});//eof
Apart from the fact that that is completely, insanely useless and with no security whatsoever, you can just exchange $.ajax() for $.post() and do like this:
var loginEmail = $('#email').val();
var loginPassword = $('#password').val();
$.post('login.php',{email:loginEmail,password1:loginPassword},function(data) {
console.log(data);
})
So I've got a system in place to post comments to a page, where they are all called from the database and displayed on the page. Each comment has a value called "rating" which is defaulted to 1, and each comment has up and down arrows to the left of it for rating up and rating down which would increase and decrease the rating respectively. Now, I've figured out how to increase and decrease the numbers, but the way I have it, all posts' ratings increase at the same time, regardless of which post I rate.
This is my "rateup" function:
$(function () {
$('#rateup').click(function() {
var request = $.ajax( {
type: "POST",
url: "rateup.php"
});
request.done(function( msg ) {
return;
});
request.fail(function(jqXHR, textStatus) {
});
location.reload();
});
});
This is my rateup.php file:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db_posts";
$tablename = "posts";
// Connection to database
$connection=mysqli_connect("$servername","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno()) {
echo 'NOT_OK';
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Increasing the current value with 1
mysqli_query($connection,"UPDATE $tablename SET rating = (rating + 1)");
mysqli_close($connection);
echo 'OK';
?>
I know that the reason it's incrementing all posts' ratings is because I'm not specifying which post to increment, and that's what I need help with. How do I specify which post is rated when the links to the left of said post are clicked?
The links are echoed like so:
echo " <a class='noStyle' id='rateup' href='index.php'>▼</a>";
It's just a unicode up arrow that's echoed with the post.
Thanks!
You need to specify which link you are clicking and send that through the form.
You can add a data-* tag to your links to do this:
echo " <a class='noStyle' id='rateup' href='index.php' data-id='".$commentID."'>▼</a>";
Then you can get that value when you submit the form and send it as data:
$(function () {
$('.rateup').click(function() {
var id = $(this).data('id');
$.ajax( {
type: "POST",
data: "id=" + id,
url: "rateup.php"
});
location.reload();
});
});
Then you can retrieve this through the form:
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db_posts";
$tablename = "posts";
// Connection to database
$connection=mysqli_connect("$servername","$username","$password","$dbname");
// Check connection
if (mysqli_connect_errno()) {
echo 'NOT_OK';
//echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['id'];
// Increasing the current value with 1
mysqli_query($connection,"UPDATE $tablename SET rating = (rating + 1) WHERE commentID = '".$id."'");
mysqli_close($connection);
echo 'OK';
?>
I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}
how can I save all my datatable data to my database?, im using jquery and php to do this dynamic.
$('#bot_guar').click( function () {
//var rows = $("#tabla1").dataTable().fnGetNodes();
var oTable = $('#tabla1').DataTable();
var data1 = oTable.rows().data();
//alert(data1.length);
$.ajax({
type:"POST",
dataType:'json',
url: "<?= Router::Url(['controller' => 'cab_facturas', 'action' => 'addDetFac'], TRUE); ?>/",//teacher//getdata/3
data:data1,
success: function(data){
alert(data);
}//success
});
});
this is what I had to POST the data from datatable, but I dunno why is the function to send to my php function that will insert.
You can consume the data object sent from your AJAX call as POST parameters or query string parameters depending on your settings. Consider you want to access firstname, lastname and email from your server side script. It can be done using:
$firstname = _POST['firstname'];
$lastname = _POST['lastname'];
$email = _POST['email'];
Now, Connect to your database and insert this data through your php script:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Its good practice to send a response to your call back functions so you can do this:
echo json_encode(array('status'=>"Success", message=""));
Your call back function will contain the data sent back from the php file. Since we are sending back a json string, we can make an object of it like this:
var myCallbackFunction = function(data){
var d = $.parseJSON(data)[0];
if(d.Status=="Success"){
//reload your datatable ajax
}else{
alert(d.message);
}
}
I hope that helped!