Ajax To PHP converter get value from ajax - javascript

i need help, here my code :
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getstok.php?secretkey=123&sku=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Masukkan kode barang / SKU:</b></p>
<form>
Kode Barang: <input type="text" onkeyup="showHint(this.value)">
</form>
<div id="txtHint"></span>
</body>
</html>
What I need is:
I want to hide this "secretkey=123" so visitor cannot see my secret key
when call "xmlhttp.send();" return the value and I want to convert it to php like example
$getxmlhttp = xmlhttp.send();
when I type something it will be call function, but when I press enter that refresh, how to disable the enter or what the best suggestion for me.
this is my site sample:
http://stok.tk
for example type "YI 067"

1 : You can't. The browser (and so the visitor) can always know wich page is called with wich URL and parameters
2 : You can't do it like that. You need to get the value of your request into getstok.php with the super global variables $_GET['your var']
3 : It's reloading the page because it's sending your form. By default it send it to the same page. Just remove your <form>

Related

Why does not the Ajax response shown in innerHTML and changes back to the original text?

I am trying to get a response from a local file and display it. However, the response text changes back to the original text. Any help would be appreciated.
<script>
function getMsg(text) {
if (text.length == 0) {
document.getElementById("msg").innerHTML = "";
return;
} else {
document.getElementById("msg").innerHTML = "sending request";
var xhttp = new XMLHttpRequest();
var filepath = "";
if (inputText == "File1") {
filepath = "file1.txt";
} else if (inputText == "File2") {
filepath = "file2.txt";
}
xhttp.open("GET", filepath, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.response);
document.getElementById("msg").innerHTML = this.responseText;
} else {
document.getElementById("msg").innerHTML = "failed";
}
};
}
}
</script>
<body>
<form onsubmit="getMsg(this.file.value)">
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
</body>
This is because you form submits normally along with your ajax and reload the page. You can prevent the form from submitting by returning false from your onsubmit handler.
<form onsubmit="getMsg(this.file.value); return false">
Welcome to Stackoverflow, by reading your code I noticed you got two main issues.
Avoid using innerHTML, it's a bad practice.
When you use innerHTML, even if your string variable is only text (no HTML tags, etc), the content is parsed by JavaScript which takes time, it might not be significant in a small app like this, but in bigger apps this has a big impact in performance.
Use innerText.
You are not preventing the default behavior of your form.
When using AJAX request, the best approach for this is to set an event listener to the form like this:
Your HTML:
<form id="file_select"><!-- Add an id to identify the form -->
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
<div id="msg"></div>
You can add an event listener in JavaScript like this:
document.querySelector("#file_select").addEventListener("submit",(event)=>{
event.preventDefault();
//Your code
});
The preventDefault() function prevents the window redirection to the action attribute of your form. (Default behavior)
Keeping code clean, reusable and simple.
This is the same function with cleaner code, you should try keeping your code easy to read so when you come back to it you understand everything perfectly.
const message = (text) =>{
document.querySelector("#msg").innerText = text; //The message div
};
document.querySelector("#file_select").addEventListener("submit",(event)=>{
event.preventDefault();
let fileValue = event.target.file.value; //The value of the file
if (fileValue != "") { //If value not empty
var xhttp = new XMLHttpRequest();
var filepath = (fileValue === "File1" ? "file1.txt" : (fileValue === "File2") ? "file2.txt" : "");
message("Filepath is: "+filepath);
xhttp.open("GET", filepath, true);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
message.innerText = this.responseText;
} else {
message.innerText = "failed";
}
xhttp.send();
}
} else { //If input is empty
message("Invalid file.");
}
});
<form id="file_select">
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
<div id="msg"></div>
Note: You can use message("text") to output the result of your AJAX request. It's up to you how to fit this to your expected behavior. Hope this helps you.

AJAX logic not working

I am new to AJAX and learning it. I am searching a food item in my HTML textbox and trying to communicate with the server to know if the item is available. The respective status of the item should be shown in the div tag below the textbox but it is not showing.
I haven't studied jQuery yet and would like to know the below things:
How to get the response from the server in plaintext using AJAX and JavaScript, and display it in the div tag below the textbox (advise the changes to be made in the code).
What change should I make in JavaScript code to send the AJAX request in POST method (I know about the changes in PHP code)?
//index.html
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Cheff's Place</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
//food.js
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.php?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send(null);
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
//index.php
<?php
header('Content-Type: text/plain');
$food = $_GET['food'];
$foodArray = array("paneer", "butter", "chicken", "tandoori", "dal");
if (in_array($food, $foodArray))
{
echo "We do have " .$food;
}
elseif($food == "")
{
echo "Kindly enter some food";
}
else
{
echo "We do not sell " .$food;
}
?>
I ran your code. It's working fine. Just replace onkeypress with onkeyup.
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
Using JQuery (Assuming you have included jquery file or cdn) :
Include the following snippet in script tag at the end of the body.
$("#userInput").keyup(function(){
$.get("index.php", { food: $("#userInput").val() })
.done(function(data) {
$("#underInput").html(data)
})
});

Auto Link shorting via PHP&AJAX (bit.ly)

I would like to build a form (VIA POST METHOD) with just one field (url - link shortening). Now the question is how and if is it possible to build a form that detects the value of the URL field is a link and automatically shortens it rather than waiting you click Send (for exmaple like the web of Bit.ly).
The main idea is once the field is an identifier that value is a proper Hyperlink is directly sends and shortens (And the field is replaced by a shortened link) it without waiting for the click on the SEND.
index.html
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a url in the input field below:</b></p>
<form>
Url: <input type="text" onkeyup="showHint(this.value)">
</form>
<p><span id="txtHint"></span></p>
</body>
</html>
gethint.php
<?php
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
if (!filter_var($q, FILTER_VALIDATE_URL) === FALSE) {
// short the link
$rand = rand(1,1000);
$hint = 'http://domain.com/'.$rand; }
echo $hint === "" ? "Not a valid URL" : $hint; ?>
I'd use jQuery for the event triggering/AJAX and https://gist.github.com/dperini/729294 for weburl regex.
I'm not that at home on pure JavaScript AJAX calls, but is
xmlhttp.open("GET")
the right way to go at it if you want to make a POST?
Anyway the main thing you're missing is
function isUrl(url){
var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
if(regex.test(url)){
return regex.test(url);
}else{
return regex.test("http://"+url);
}
}
So this should be your new index.html
<html>
<head>
<script>
var extensions = [".aero",".biz",".cat",".com",".coop",".edu",".gov",".info",".int",".jobs",".mil",".mobi",".museum",".name",".net",".org",".travel",".ac",".ad",".ae",".af",".ag",".ai",".al",".am",".an",".ao",".aq",".ar",".as",".at",".au",".aw",".az",".ba",".bb",".bd",".be",".bf",".bg",".bh",".bi",".bj",".bm",".bn",".bo",".br",".bs",".bt",".bv",".bw",".by",".bz",".ca",".cc",".cd",".cf",".cg",".ch",".ci",".ck",".cl",".cm",".cn",".co",".cr",".cs",".cu",".cv",".cx",".cy",".cz",".de",".dj",".dk",".dm",".do",".dz",".ec",".ee",".eg",".eh",".er",".es",".et",".eu",".fi",".fj",".fk",".fm",".fo",".fr",".ga",".gb",".gd",".ge",".gf",".gg",".gh",".gi",".gl",".gm",".gn",".gp",".gq",".gr",".gs",".gt",".gu",".gw",".gy",".hk",".hm",".hn",".hr",".ht",".hu",".id",".ie",".il",".im",".in",".io",".iq",".ir",".is",".it",".je",".jm",".jo",".jp",".ke",".kg",".kh",".ki",".km",".kn",".kp",".kr",".kw",".ky",".kz",".la",".lb",".lc",".li",".lk",".lr",".ls",".lt",".lu",".lv",".ly",".ma",".mc",".md",".mg",".mh",".mk",".ml",".mm",".mn",".mo",".mp",".mq",".mr",".ms",".mt",".mu",".mv",".mw",".mx",".my",".mz",".na",".nc",".ne",".nf",".ng",".ni",".nl",".no",".np",".nr",".nu",".nz",".om",".pa",".pe",".pf",".pg",".ph",".pk",".pl",".pm",".pn",".pr",".ps",".pt",".pw",".py",".qa",".re",".ro",".ru",".rw",".sa",".sb",".sc",".sd",".se",".sg",".sh",".si",".sj",".sk",".sl",".sm",".sn",".so",".sr",".st",".su",".sv",".sy",".sz",".tc",".td",".tf",".tg",".th",".tj",".tk",".tm",".tn",".to",".tp",".tr",".tt",".tv",".tw",".tz",".ua",".ug",".uk",".um",".us",".uy",".uz", ".va",".vc",".ve",".vg",".vi",".vn",".vu",".wf",".ws",".ye",".yt",".yu",".za",".zm",".zr",".zw"];
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
function isUrl(url){
var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
if(regex.test(url)){
return regex.test(url);
}else{
return regex.test("http://"+url);
}
}
function showHint(str) {
delay(function(){
str = str.toLowerCase();
var dot = str.lastIndexOf(".");
var extension = str.substr(dot);
extension = extension.split('/')[0];
var found = $.inArray(extension, extensions) > -1;
if (!isUrl(str)||!found) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}, 500)
}
</script>
</head>
<body>
<p><b>Start typing a url in the input field below:</b></p>
<form>
Url: <input type="text" onkeyup="showHint(this.value)">
</form>
<p><span id="txtHint"></span></p>
</body>
</html>
edit: Say you will start typing in http://www.example.net.. The AJAX will trigger on "http://www.example.ne" and then again when you add the last letter. To avoid that, you might try "change" instead of "keyup" event.
edit2: Now checks against list of valid domain extensions
edit3: Now waits half a second before posting the result.
edit4: Small oversight while checking for extensions, fixed with
extension = extension.split('/')[0];
Also if you want to enable users to write URL's without "http://" and similar, you'll need an edited regex or write a small hack that adds that to your string before you send it into "isUrl()".

How to check if a session is empty using javascript inside php

Also, how do i unset the session through javascript?
I have made this code with PHP:
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_POST['excel_array']['Main']['Plan1'] = array();
}
else{
$_SESSION['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_SESSION['excel_array']['Main']['Plan1'] = array();
}
So here i check if there is a session. If there is, i unset it and send the $_POST data instead. however, if there isn't one, i create it.
The problem is, i might want to call this on a button click. How would i make a code with the same functionality, but using a javascript function?
Put your php in a file on its own, called set_session.php for example:
<?php
session_start();
unset($_SESSION['Plan1']);
echo 'unset';
?>
Call it in javascript:
<script>
function unset() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("GET", "set_session.php", true);
xhttp.send();
}
</script>
<button type="button" onclick="unset()">Unset</button>
<div id="result"></div>

JSP Chat - How I can parse the value from HTML to JSP page?

I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null.
If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that.
I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem).
How I can make to populate 'textParam' with the input text value when I press the button?
PS: I need to make it with pure javascript, not with some libraries :)
The JSP which have to process is:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
My form it look like that:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
The .js file it's this:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
The problem is here:
String textParam = request.getParameter("chatMessage");
I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js:
String textParam = request.getParameter("message");

Categories