Ajax, JS function returning undefined value [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I am very new to all of this, I am tying to learn Ajax as well as Javascript, I am getting the value from a php file, but when I try to return the value in the method I get a undefined value which i log in the console., I am after trying a lot of thing but with no success. Can some one please educate me on this. And please criticize me code im sure there is a lot of bad practice.
Thanks
function checkEmail(){
var xhttp;
var status;
xhttp = new XMLHttpRequest();
var email = document.getElementById('email2').value;
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlResponse = xhttp.responseText;
status = xmlResponse;
}
};
xhttp.open("GET", "php/ajaxCom.php?email="+email, true);
xhttp.send();
return status;
}
<?php
include 'base.php';
$status;
$email_in_use = $_GET['email'];
$query = mysqli_query($link, "SELECT * FROM users WHERE email='".$email_in_use."'");
if(mysqli_num_rows($query) > 0){
$status = "false";
}else{
$status = "true";
}
echo $status;
?>
This is where I call the checkEmail
function getStatus(field, name, value) {
var status = null;
if (!field.attr('required')) return null;
if (!value) status = 'Please fill out the required field: ' + name;
else if (emailField.test(name) || emailField.test(field.attr('type'))) {
var b = checkEmail();
console.log(b);
if (!emailValue.test(value)) {
status = 'Please enter a valid email address for: ' + name;
}else if ( b == "false"){
alert("im here");
status = 'Please enter a valid email this email already has an acount';
}
}
return status;
}
update
The stats alert is shown correctly but the console log is still showing undefined
function getStatus(field, name, value) {
var status = null;
if (!field.attr('required')) return null;
if (!value) status = 'Please fill out the required field: ' + name;
else if (emailField.test(name) || emailField.test(field.attr('type'))) {
var b;
checkEmail(function(status) {
alert('Status: ' + status);
b = status;
});
console.log(b);
if (!emailValue.test(value)) {
status = 'Please enter a valid email address for: ' + name;
}else if ( b == "false" || b == "true"){
alert("im here");
status = 'Please enter a valid email this email already has an acount';
}
}
return status;
}

You're returning status immediately, where as the actual AJAX calls returns asynchronously.
You need to change your flow so that checkEmail would accept a callback function as parameter instead of returning it. Something like that:
function checkEmail(callback) {
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlResponse = xhttp.responseText;
status = xmlResponse;
callback(status);
}
};
...
checkEmail(function(status) {
alert('Status: ' + status);
});

Related

Undefined index error in ajax using javascript

I am sending data through ajax it is working properly using jquery but JavaScript code is giving undefined error
function send_message() {
var name = document.querySelector("#name").value;
var email = document.querySelector("#email").value;
var mobile = document.querySelector("#mobile").value;
var message = document.querySelector("#message").value;
if (name == "") {
alert('Please enter name');
} else if (email == "") {
alert('Please enter email');
}
else if (mobile == "") {
alert('Please enter mobile');
}
else if (message == "") {
alert('Please enter message');
} else {
var ajax = new XMLHttpRequest();
ajax.open("POST", "send_message.php", true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
console.log(response);
alert(response);
}
};
var data = 'name='+name+'&email='+email+'&mobile='+mobile+'&message='+message;
ajax.send(JSON.stringify(data));
}
}
the error code is
<br />
<b>Notice</b>: Undefined index: name in <b>D:\xampp\htdocs\webmakeup\send_message.php</b> on line <b>4</b><br />
<br />
<b>Notice</b>: Undefined index: email in <b>D:\xampp\htdocs\webmakeup
send_message.php is the file I am sending data to.
This is my php code
require('connection.inc.php');
require('functions.inc.php');
$name=get_safe_value($con,$_POST['name']);
$email=get_safe_value($con,$_POST['email']);
$mobile=get_safe_value($con,$_POST['mobile']);
$comment=get_safe_value($con,$_POST['message']);
$added_on=date('Y-m-d h:i:s');
mysqli_query($con,"insert into contact_us(name,email,mobile,comment,added_on) values('$name','$email','$mobile','$comment','$added_on')");
echo "Thank you";
?>
Your PHP endpoint is expecting application/x-www-form-urlencoded data not JSON.
You can use a URLSearchParams object to send that type of data.
var ajax = new XMLHttpRequest();
ajax.open("POST", "send_message.php", true);
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
console.log(response);
alert(response);
}
};
var data = new URLSearchParams ({name,email,mobile,message});
ajax.send(data);
Don't JSON.stringify what you send.
Wrap each variable in encodeUriComponent.
Don't add a space after the equals.
Try:
var data = 'name=' + encodeURIComponent(name)
+ '&email=' + encodeURIComponent(email)
+ '&mobile=' + encodeURIComponent(mobile)
+ '&message=' + encodeURIComponent(message);
ajax.send(data);

JavaScript function reads parameter differently than I expected

I have 2 functions. I'm trying to pass a text value from editTest() into the function populateEditTestTemplate(x). Right before I pass in the value, I am logging it. This log shows "1" in the console. When I log the value after it is passed into populateEditTestTemplate(x), the log shows [object Text]. Why is this?
editTestButton.onclick = function editTest() {
console.log("editing test");
if (getSelectedTestIds().length > 1)
{
alert("You can only edit one test at a time!");
}
else if (getSelectedTestIds().length < 1)
{
alert("Please select a test to edit!");
}
else
{
if (!isHidden("new-test-template")) {
toggleHide("new-test-template");
testInProgress = false;
}
if(testInProgress == false) {
testInProgress = true;
toggleHide("edit-test-template");
selectedTestId = getSelectedTestIds()[0];
console.log(selectedTestId); // <----ouputs "1" ***********************
populateEditTestTemplate(selectedTestId);
}
}
}
and
function populateEditTestTemplate(testId)
{
console.log(testId); // <----ouputs [object Text] ***********************
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var data = JSON.stringify(xhr.responseText);
console.log("xhr response: " + data);
}
}
console.log(xhr.open("POST", "./db-queries/get-test.php",true));
xhr.send("testId=" + testId);
}

How Can I Use 2 $_POST without them interfering with one another?

I'm new to Web Development, and I am trying to understand why when I use 2 $_POST how the second is concatenating with the first. This is causing me to receive an error:
Uncaught SyntaxError: Unexpected number in JSON at position 11
at JSON.parse ()
at XMLHttpRequest.AJAX_handle_response (HangManMath.js:77)
Any Other tips with the code are appreciated as well as resources that will help me better understand AJAX programming.
I don't know that much about PHP, but I have tried everything. My Code is below.
$_POST = json_decode(file_get_contents('php://input'), true);
$response = "";
if (isset($_POST['guess']) && $_POST['guess'] !== '') {
$guess = $_POST['guess'];
if ($guess === 3)) {
$response = "Correct";
}
else {
$response = "Incorrect";
}
$response = json_encode($response);
header('Content-Type: application/json');
echo $response;
}
$_POST = json_decode(file_get_contents('php://input'), true);
if (empty($_POST["current_number"])) {
if($_POST["response-p"] === "Correct!"){
$current_number = 2; // $_POST["current_number"];
$current_number = intval($current_number);
$current_number++;
}
else {
$current_number = 1;//$current_number;
}
$current_number = json_encode($current_number);
echo $current_number;
}
//JAVASCRIPT
function Current_question(current, response){
current_number = document.getElementById(current).value;
response_p = document.getElementById(response).value;
console.log("Response: " + response_p);
console.log("Element id: " + current_number);
let req1 = new XMLHttpRequest();
req1.addEventListener("load", Current_question_status);
req1.open("POST", "HangManMath.php", true);
req1.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req1.send(JSON.stringify(current_number, response_p));
}
function Current_question_status(){
console.log("Handeling Current_Question");
let current_number = this.responseText;
console.log("Before JSON parse..." + current_number);
current_number = JSON.parse(current_number);
console.log("After JSON parse..." + current_number);
current_number = parseInt(current_number);
if(AJAX_handle_response === "Correct"){
current_number++;
}
document.getElementById("current_number").innerHTML = current_number;
}
// Start an AJAX request with a JSON payload,
// sent via the POST http method to the server
// script (process_guess.php).
function AJAX_start(payload){
console.log("Sending new value to the server.");
console.log(payload);
let req = new XMLHttpRequest();
req.addEventListener("load", AJAX_handle_response);
req.open("POST", "HangManMath.php", true);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-
8");
req.send(JSON.stringify(payload));
}
// Handles the server's response, when it is received.
function AJAX_handle_response(){
console.log("Handling server response: ");
let payload = this.responseText;
console.log("... Response text: " + payload);
if(payload === "")
return false;
payload = JSON.parse(payload);
// decode the guess and result from the server
let result;
if(payload === "Incorrect"){
result = "Incorrect!";
}
else{
result = "Correct!";
}
document.getElementById("response-p").innerHTML = result;
// Now we want to clear the input box as well,
// to make room for the next guess.
document.getElementById("guess").value = "";
return result;
}
I expect "Correct" for one POST and "3" for the other POST
I am actually getting "Correct"3

Using Ajax/XMLhttprequest to send data to a php file with mail function

I have been following this tutorial (https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) but I had no luck. I am trying to communicate with a php file with a javascript file using XMLhttpRequest. This is the code bellow. I still dont understand how to fully transfer the data across.
HTML
form id="uDF" method="post" onsubmit="submitValidation()">
JavaScript
function submitValidation(){
var data = [document.forms ["uDF"] ["uDFName"].value, document.forms ["uDF"] ["uDFNumber"].value,
document.forms ["uDF"] ["uDFEmail"].value, document.forms ["uDF"] ["uDFSubject"].value,
document.forms ["uDF"] ["uDFMessage"].value,]
console.log(data);
var char = ''; // variable used to check whether email has #
var x;
var isEmail = false;
var isNotEmpty = false;
//for loop checks email for # char
for(x = 0; x<data[2].length;x++)
{
char = data[2].charAt(x);
if(char === "#"){
isEmail = true;
break;
}
}
var i;
//for loop check if data is collected
for(i=0;i < 5;i++){
if(data[i] === ""){
isNotEmpty = false;
}else{
isNotEmpty = true;
}
}
if(isEmail === true && isNotEmpty === true)
{
var httpRequest;
httpRequest = new XMLHttpRequest();
if(!httpRequest){
return false;
}
httpRequest.onreadystatechange = function(){
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200)
{
var response = JSON.parse(httpRequest.responseText);
}
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]))
}
}else if (!isNotEmpty){
alert("empty fields");
}else if(!isEmail){
alert("Please enter valid email!");
}
}
PHP
$uDFName = (isset($_POST['uDFName'])) ? $_POST['uDFName'] : '';
$uDFNumber = (isset($_POST['uDFNumber'])) ? $_POST['uDFNumber'] : '';
$uDFEmail = "my#email";
$uDFSubject = (isset($_POST['uDFSubject'])) ? $_POST['uDFSubject'] : '';
$uDFMessage = $uDFName . "\r\n" . $uDFNumber . "\r\n" . "just testing";
$message = wordwrap($message, 70, "\r\n");
mail($uDFEmail, $uDFSubject, $uDFMessage);
You have to open and send the request outside of the event handler function. The onreadystatechange handler only executes when the ready state of your request changes.
If you don't open and send the request, the handler function is not executed, and you won't see any results.
This solution should work:
var httpRequest = new XMLHttpRequest();
// this function executes whenever the ready state of the request changes
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
}
}
// open the request ...
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// ... and send it
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]));

Value not found in php

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}
you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);
You missed an equal sign '=' in your javascript at your mailid parameter.

Categories

Resources