I am building an account sign-up page that checks the users email address against the db to ensure said user isn't creating a duplicate account. Using ajax to report if email exists in the db. When typing the email address into the form I always get "email is ok". Meaning that it doesn't exist in the db. However, it is incorrect. If I assign the email as a variable in the php parser like $email="email#exists.com" then it will actually report back the correct result. I'm guessing that the parser isn't getting the value from the form in order to add to the query. Do you know why this isn't working?
<input type="text" id="password" class="form-control" name="password" value="" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" placeholder="password" autocomplete="off" required />
Ajax:
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "email_check.php";
var fn = document.getElementById("firstname").value;
var ln = document.getElementById("lastname").value;
var e = document.getElementById("email").value;
var pwd = document.getElementById("password").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
and the parser:
<?php
include 'db.php';
$test= $_POST['email'];
$sql="SELECT email FROM users where email = '$test' LIMIT 1";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
echo 'email is in use.';
exit();
} else if(mysqli_num_rows($result) < 1){
echo 'email is ok';
exit();
}
?>
You didn't add the email field to your vars when you sent the request, in this line:
var vars = "firstname="+fn+"&lastname="+ln;
You need to send email to your parser not firstname/lastname
var vars = "email="+e;
Related
I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;
<body>
<form>
<label for="txtLength">Length</label>
<input type="text" id="txtLength" name="txtLength"><br><br>
<label for="txtWidth">Width</label>
<input type="text" id="txtWidth" name="txtWidth"><br><br>
<input type="hidden" name="submitted" value="1">
<input type="button" name="Calculate" value="Calculate" onclick="calArea();">
</form><br><br>
<div id="showArea">Enter Values and click Calculate.</div>
<script type="text/javascript">
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.readyState == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.send(len&wid&sub);
}
</script>
</body>
This code is for the server side.
<?php
print_r($_POST);
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
?>
Even tried so many codes, It doesn't send the data to server side.
I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.
Client-side code;
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
}
Server-side code;
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
len&wid&sub
Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.
You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.
PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.
The URLSearchParams API will generate URL Encoded data for you.
e.g.
xhttp.send(new URLSearchParams({ len, wid, sub }));
Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.
You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.
You also need to set the content type so this data will be parsed correctly.
So change
xhttp.send(len&wid&sub);
should be:
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);
I am not able to send parameters to server file via ajax. i have checked comment.php with get parameters its working fine. But with ajax post parameter are not received by comment.php and else condition executes
Request Payload inside headers show url parameters received by server but when i echo $_POST array die(print_r($_REQUEST)); it gives me empty array
Here is the code i am using
<input type="text" name="comment" id="q_comment" placeholder="Add a comment" onKeyPress="postComment('q_comment')" autocomplete="off">
<script>
function $(id){
return document.getElementById(id);
}
document.onkeydown = function(event){
key_code = event.keyCode;
}
function postComment(comment_type){
if(key_code == 13){//If enter is pressed
if(comment_type == "q_comment"){//if comment added in question
var comment = $("q_comment").value;
}
else{//if comment added in answer
var comment = $("a_comment").value;
}
if(comment != ""){
var question_id = "<?php echo $id; ?>";//Returns current question id
//var params = "comment="+comment+"&question_id="+question_id;
var params = "question_id="+question_id+"&comment="+comment;//data to send to server
var ajax = new XMLHttpRequest();
ajax.open("POST","/ajax_call_files/comment.php",true);
ajax.setRequestHeader("Content-type","application/x-www-url-encoded");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var response = ajax.responseText;
console.log(response);
}
}
ajax.send(params);
console.log(params);
}
}
</script>
Comment.php
if(isset($_POST['comment']) && isset($_POST['question_id']) && !empty($_POST['comment']) && !empty($_POST['question_id'])){
require_once('../db_conn.php');
$user_id = $_SESSION['id'];
$comment = substr($_POST['comment'],0,530);
$comment = htmlspecialchars($comment);
$comment = mysqli_real_escape_string($conn,$comment);
$question_id = preg_replace('#[^0-9]#','',$_POST['question_id']);
$sql = "INSERT INTO comments(question_id,user_id,comment,date_time) VALUES('$question_id','$user_id','$comment',now())";
$query = mysqli_query($conn,$sql);
if($query){
echo mysqli_insert_id($conn);
}
else{
echo "Comment not added. Try again later";
}
}
else{
echo "no data recieved";
}
i have rewrite rule on file from which i am calling ajax. could it be the reason why url parameters are not received by the server
this is the rule i am using
RewriteRule ^questions/([0-9]+)/([a-zA-Z0-9_]+) questions.php?id=$1&title=$2 [NC,L]
Change the line.
ajax.setRequestHeader("Content-type","application/x-www-url-encoded");
to
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
After
ajax.open("POST","/ajax_call_files/comment.php",true);
you need to add the url parameter as:
ajax.send(params);
After the above line of code when you are using the open() function, after you set the headers of the ajax call
At present you are trying to send the the url parameters to the server after ajax call
I honesty did every possible search, watched lots of tutorials, but still cant make it work. The mistake is somewhere in connetion between javascript and php. The strange point is that connection is successfull and script works if I click the submit button when the page is in a process of reloading.
Please, help.
I call two variables, $l1 and $l2 from the php require-once which do some work on the page, then I use them in Java script to send to PHPfile onclick of submit button;
Button:
<input class ="button vote" type = "submit" onClick= "javascript: somefunction();" value = "do it" />
Function:
function somefunction(){
var hr = new XMLHttpRequest();
var url = "index.php";
var wn = "<?php echo $l1 ?>";
var ls = "<?php echo $l2 ?>";
var vars = "wn="+wn+"&ls="+ls;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // execute the request
document.getElementById("status").innerHTML = "processing...";
}
php acceptor on the same page:
<?php if (isset ($_POST ["wn"])){
$wnn = $_POST['wn'];
$lss = $_POST['ls'];...
try this:
var wn = document.getElementById("wn").value;
var ls = document.getElementById("ls").value;
I presume you ar calculating these either diectly, or from a $_SESSION variable perhaps? When you view the source on the completed page check if the variables are present, perhaps just after you assigne the variables within php.
<?PHP
if (isset($l1) && !empty($l1)) {
echo "L1 is $l1";
} else {
echo "L1 wasnt set";
}
?>
then make sure the value up top matches that you're seeing in your javascript
I have two pages. 1st page has two text forms like so:
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
It pushes the information into page number two using javascript like so (note this is on the same page as the code above):
<script>
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
var url = "location.php?uname=" + uname + "&ulocation=" + ulocation;
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
</script>
So the problem is this, the php scripts on the page that does all server communication is not reading and storing the variables from this post request into my database.(my other get methods that view items in the database works fine)
if (isset($_POST['uname']))
{
$name = $_POST['uname'];
$location = $_POST['ulocation']
}
then the query goes somehting like
//$table and the other undefined variables are the names of my table & columns
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
Basically I'm trying to get that query to work. If i remove the If statement, it stores $name to the database but not $location.
EDIT:
I forgot to add
<div id="result">
</div>
You are sending a GET.
to send a POST try:
[edited] perform the functions that order
function XHR(){
if(typeof XMLHttpRequest !=="undefined"){
try{ return new XMLHttpRequest(); } catch (e){}
}
if(typeof ActiveXObject !=="undefined"){
try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
}
return false;
}
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
var url = "location.php";
xmlhttp = XHR();//Fixed
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//Fixed
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4) {
if(xmlhttp.status==200){
document.getElementById("result").innerHTML = xmlhttp.responseText;
} else {
document.getElementById("result").innerHTML = "ERROR:"+xmlhttp.status;
}
}
};
xmlhttp.send("uname=" + uname + "&ulocation=" + ulocation);
}
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
Your missing a form method. In your case you wish:
<form name='NameForm" method="POST">
If this does not resolve your issue, then download and use firebug for firefox or chrome console to debug javascript errors.
There will be no output of errors in JS to the text. You will need to use a debug console.
perform an insert via html form
I would modify your HTML to:
<form name="NameForm" method="POST">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
<input type='submit' name='SubmitForm' value='SUBMIT THIS FORM'>
</form>
Then my PHP code:
<?php
if(isset($_POST['SubmitForm'])){
$Name = $_POST['uname'];
$Location = $_POST['ulocation'];
// Perform validation for these inputs, check if empty, set correctly ETC
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
}
then call your Javascript function inside your PHP script; or perform an ajax/jquery call to run the insert without the need of a submit button
I have a simple form that sends data using jQuery/Ajax/PHP. The PHP code validates the input before it sends it to the database and returns an error message to the response div if the input is invalid.
It works great on my computer and on my own server. But when I upload it to the client's server it doesn't work as expected. I noticed the following when I access the page from the client's server:
The validation result is being sent to the response div only if ALL the input fields have values. If any of the fields is empty, then nothing happens and no validation message is returned.
It doesn't seem to be a machine issue because I'm using the same computer to access the 3 copies, the one on my localhost, the one on my server, and the one on the client's server.
Here is the code; the jQuery:
$(document).ready(function() {
$('#signup').click(function() {
var queryString = 'ajax=true';
var txtName = encodeURIComponent($('#txtName').val());
if(txtName.length > 0){
txtName = txtName.replace(/\%/g, '-');
}
var txtEmail = escape($('#txtEmail').val());
var txtPhone = encodeURIComponent($('#txtPhone').val());
if(txtPhone.length > 0){
txtPhone = txtPhone.replace(/\%/g, '-');
}
var txtPhoneCode = encodeURIComponent($('#txtPhoneCode').val());
if(txtPhoneCode.length > 0){
txtPhoneCode = txtPhoneCode.replace(/\%/g, '-');
}
queryString = queryString + '&txtEmail=' + txtEmail;
queryString = queryString + '&txtName=' + txtName;
queryString = queryString + '&txtPhone=' + txtPhone;
queryString = queryString + '&txtPhoneCode=' + txtPhoneCode;
$.ajax({
type: "GET",
url: 'send.php',
data: queryString ,
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
The PHP page:
<?php
if(isset($_GET['ajax']) && ($_GET['ajax'] == 'true')){
$name = trim($_GET['txtName']); // coming from input text
$email = trim($_GET['txtEmail']); // coming from input text
$phone = trim($_GET['txtPhone']); // coming from input text
$phonecode = trim($_GET['txtPhoneCode']); // coming from a select
if(strlen($name) == 0){
echo 'Please enter your name';
}
elseif(strlen($email) == 0){
echo 'Please enter your email';
}
elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $email)){
echo 'Please enter a valid email';
}
elseif(strlen($phonecode) == 0){
echo 'Please select phone code';
}
elseif(strlen($phone) == 0){
echo 'Please enter your phone';
}
elseif(!preg_match("/^[0-9]*$/i", $phone)){
echo 'Please enter a valid phone';
}
else{
require('config.php');
// send to mysql db
$email = stripslashes($email);
$name = urldecode(str_replace('-', '%', $name));
$phone = urldecode(str_replace('-', '%', $phone));
$phonecode = urldecode(str_replace('-', '%', $phonecode));
$dt = gmdate("Y-m-d H:i:s");
$sql = "insert into subscribers(datecreated, name, email, phone, phonecode) values('$dt', '$name', '$email', '$phone', '$phonecode')";
$result = mysql_query($sql) or die('Error: Failed to save subscription!');
// redirect
echo '<script>setTimeout(function(){ window.location = "thankyou.html#ty"; }, 0);</script>';
}
}
?>
You are not posting data to the server since you are setting type: "GET".
This means that an HTTP GET request is sent, not HTTP POST. GET requests are typically cached by the client and therefore you may experience that no request is sent at all (when some combinations of field values are used) because the response of that request is already in the client's cache.
You should change your code (both javascript and php) to use HTTP POST instead. The reason for this is twofold:
POST responses are not cached, so a new request will be sent each time you submit.
GET should not be used for requests that may have side effects.