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);
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'.
I'm developing an PHP-MySQL-JS platorm. I'm doing now the profile page and there the user can update his info.
My code is:
HTML
<form>
//rest of the form.
//The submit button.
<button id="profile_submit" style="margin-left: 500px; margin-top: 10px;" class="logout" type="submit"><b>Guardar cambios</b></button>
</form>
JavaScript
$( document ).ready(function() {
$('#profile_submit').click(function(){
var name1 = $('#name1').val();
var name2 = $('#name2').val();
var user = $('#user').val();
var email = $('#email').val();
if(name1 != '' && name2 != '' && user != '' && email != '' ){
$.ajax({
url: '../controller/updateuser.php',
method: 'POST',
data: {name1: name1, name2: name2, user: user, email: email},
success: function(msg){
if (msg == '1'){
//Error
alert("Another user is using this email already");
} else {
//Se registro
alert("Updated");
setTimeout(function(){location.href= "workspace.php"} , 1000);
}
}
});
}
});
});
PHP - general
public function update_user($name1, $name2, $user, $email){
$res = $this->conexion->query("select USR_EMAIL from usr_usuario where USR_EMAIL = '".$email."' and USR_DELETE = '0' and USR_ID <> '".$_COOKIE['USR_ID']."' ");
if(mysqli_num_rows($res)>0)
{
//Email used
echo '1';
}else{
//Update user
$this->conexion->query("UPDATE usr_usuario SET USR_USERNAME = '".$user."', USR_NAME = '".$name1."', USR_NAME2 = '".$name2."', USR_EMAIL = '".$email."' WHERE USR_ID = '".$_COOKIE['USR_ID']."' ");
}
}
PHP - update.php
<?php
require("../modelo/conexion.php");
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$user = $_POST['user'];
$email = $_POST['email'];
$object = new conexion();
$object -> actualizar_usuario($name1, $name2, $user, $email);
$object -> cerrar();
?>
Well, when the user clicks on the button with id="profile_submit", the JS read the info in the inputs and sends it to update.php and it calls the update_user in general php file.
When the user insert an email used already it works perfectly, but, when all is okay, the sql UPDATE works but the rest of the code(PHP and JS) don't sends nothing to the user.
I don't know why this happens...
Help please.
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 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);
}
}
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
}
});