Vanilla JS+AJAX - check whether a value already exists - javascript

I've got a form, which contains an input (a title for a post). I need that input to be filled with a value that doesn't exiest already in my database, so what I'm trying to do is requesting an AJAX call, to check on the fly whether that post title is already created, activated by "onChange" event.
Here is my Vanilla JS\AJAX code:
function checkEx(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function checkExNow(xhttp) {
document.getElementById("pcp_ex").innerHTML = xhttp.responseText;
}
And here is my HTML input:
<input onchange="checkEx('inc/ajax/pcp_check_ex_value.php', checkExNow)" name="pcp_name" type="text" placeholder="Post Title"> <div id="pcp_ex"></div>
Problem is, I have to find a way to send the input's value, in order to check it with my database on that PHP file.
Please, teach me how to do this using vanilla JS.
Thank you in advance!

You need to also send to your function the current value of the input field
function checkEx(url, cFunction, valueToCheck) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url+"?check="+valueToCheck, true);
xhttp.send();
}
<input onchange="checkEx('inc/ajax/pcp_check_ex_value.php', checkExNow, this.value)" name="pcp_name" type="text" placeholder="Post Title"> <div id="pcp_ex"></div>
Here you could check a complete example.

Thanks to your help, I managed.
For those who reached that post with similar issue, wondering how to do this, this is how I managed:
JS:
function checkEx(url, cFunction, valueToCheck) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url+"?check="+valueToCheck, true);
xhttp.send();
}
function checkExNow(xhttp) {
document.getElementById("pcp_ex").innerHTML = xhttp.responseText;
}
HTML:
<input onchange="checkEx('inc/ajax/pcp_check_ex_value.php', checkExNow, this.value)" name="pcp_name" class="reg_input" type="text" placeholder="Post Title">
<span id="pcp_ex"></span>
PHP:
$exe = $_GET['check'];

Related

Parsing JSON Array to print specific elements

Im currently trying to parse JSON data from this api in JS but im not sure how to. As of right now when I press any buttons to give me the data, it prints the arrays out rather than the specific data I want. Ive tried to use the JSON Parse function to retrieve the specific data but it seems its not working. Any help would be greatly appreciated! URL to the API docs: https://www.balldontlie.io/#get-all-players
//Loads Player Data
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("players").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
var data = JSON.parse(xhttp.responseText);
console.log(data["last_name"])
xhttp.send();
}
//Loads Game Data
function loadGames() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("games").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/games", true);
xhttp.send();
}
//Loads Team Data
function loadTeams() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teams").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/teams", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body style="background-color:peachpuff;" >
<center>NBA STATS</center>
<center><marquee behavior="scroll" direction="right" scrollamount="12.5">Data Extracted From BDL API</marquee></center>
<center> View API Docs </center>
<script src="main.js"></script>
<div id="players">
<button type="button" onclick="loadPlayers()">View Players</button>
</div>
<div id = "teams" >
<button type="button2" onclick="loadTeams()">View Teams</button>
</div>
<div id ="games">
<button type="button3" onclick="loadGames()">View Games</button>
<div>
</body>
</html>
You should parse JSON in xhttp.onreadystatechange, that's a callback when request data success.
For the players data as example, it is an object with data and meta, and the players is in data key which is an Array, so you need to loop inside the array to print the values that you needed.
Here's the example for loadPlayers(). You can apply the same concept to loadGames and loadTeams, please let me know if you still having questions.
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// parse JSON after response
var players = JSON.parse(this.responseText);
// get 'data' key inside response
var playersData = players.data;
// loop all the players
for (var player of playersData) {
// print last_name to the #players element
document.getElementById("players").innerHTML += "<br />" + player['last_name'];
}
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
xhttp.send();
}
In function loadPlayers()
data is an array not object

Page submission state doesn't change

I have a form like this:
function nametst(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("namevalidity").innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "nametst.php?=namerequest" + str, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
function mailtst(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("mailvalidity").innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "mailtst.php?=mailrequest" + str, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
function submittst(){
nametst(document.getElementsByName('name')[0].value);
mailtst(document.getElementsByName('email')[0].value);
return xls;
}
var xls;
function submittes(callback){
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
callback(httpRequest.responseText);
}
};
httpRequest.open('POST', "submitform.php", true);
httpRequest.send();
}
submittes(function (result) {
if (result === "yes"){
xls = true;
document.getElementById("submitanswer").innerHTML = "true";
}
else{
xls = false;
document.getElementById("submitanswer").innerHTML = "false";
}
});
<form method="POST" onsubmit= "return submittst();" action = "welcome.html">  
  Name: <input type="text" name="name" onblur="nametst(value)">
<span id="namevalidity"></span> </p>
email: <input type="text" name="email" onblur="mailtst(value)">
<span id="mailvalidity"></span> </p>
<input type="submit" value="submit">
<p> form validity: <span id="submitanswer"></span> </p>
and if the name and email are valid, submitform.php returns "yes".
When I type wrong name or email the errors will appear. So far, so good. But the form validity is always false, and it won't change even when I click "submit" button. When I set default value for name and email and they are valid, the form validity remains true.
Why does this happen?
And how can I solve it?
so, I knew that the problem was because of callback method. since there was no answer to my question, I'll use synchronous mode without these callbacks.

AJAX request failed

function ajax() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
alert(this.responseText);
}
};
}
xhttp.open("POST", "abcdef.xyz/abc/logincheck.php?mail=abc#gmail.com&password=abc", true);
xhttp.send();
<p id="demo">
The content of the body element is displayed in your browser.
</p>
<button onclick="ajax()">
Click on me!
</button>
I have a code as seen above and the ajax operations do result in failure. What is wrong with my code? The text in p never changes.The php file starts like this:
<?php
$mail = $_POST["mail"];
$password = $_POST["password"];
xhttp.open() and xhttp.send() need to be inside the ajax() function.
function ajax() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
alert(this.responseText);
}
};
xhttp.open("POST", "abcdef.xyz/abc/logincheck.php?mail=abc#gmail.com&password=abc", true);
xhttp.send();
}
due to xhttp.open and send are define out side of function block.
xhttp.open("POST", "abcdef.xyz/abc/logincheck.php?mail=abc#gmail.com&password=abc", true);
xhttp.send();

send content to other page using script

I have written a code in script which is given below.
function myFunction(a) {
var k=a;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ques").innerHTML = this.responseText;
}
};
xhttp.open("GET", "retrieveQuestion.php?question=" +a, true);
xhttp.send();
var q="<td><input type='text' name='answer' id='ans' placeholder='submit your answer here'/></td>" ;
document.getElementById("t2").innerHTML=q;
var answ = document.getElementById("ans").value;
var z="<td align='center'><input type='button' value='submit' onclick='myfunc1(k,answ)'/></td>";
document.getElementById("t3").innerHTML=z;
}
function myfunc1(q1,a1)
{
xhttp.open("GET", "checkanswer.php?question=" +q1 + "&a1=" +a1, true);
xhttp.send();
}
Now when i click on submit button it did not redirected to checkanswer.php
can anyone help me in this problem.
Using xhttp.open is sending a background request to checkanswer.php, rather than actually redirecting to it. You'd need to use something like window.location instead.

Div Cleared When Page Fully Loads

I am using a JavaScript & Ajax to make a php call to return data from my database. The call returns the data as it should, but when the page fully loads the <div> tags value is cleared.
What do I need to change in my syntax so that the div tag retains the value echo from the php file? I checked the Console and it is only showing page load info and nothing related to this issue (at least not that I saw).
<form id="form1" method="post">
<div id="results"> </div>
<div style="padding-top: 10px;"><input type="submit" value="Submit" onclick="MakeQuery()" /></div>
<script type="text/javascript">
var xhttp;
function MakeQuery()
{
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){ if (xhttp.readyState == 4 && xhttp.status==200)
{ document.getElementById("results").innerHTML = xhttp.responseText; } }
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}
</script>
</form>
I think you need to prevent the actual form submit before using AJAX:
var xhttp;
function MakeQuery(event) {
event.preventDefault(); // Cancel form submit, use AJAX
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}

Categories