I am learning JavaScript without jQuery.
Right now I am trying to pass some data from an input field to php and than pass a $variable from php to javascript. In jQuery this is easy with $.ajax.
But how do I do this with ONLY JavaScript? Here is my attempt. Right now I only want to pass the $_POST content from the inputfield. I didn't do any validation at this moment.
My plan is to make a validation with php and then pass an error message or more than one. Or in case of success an success message.
But out of my console log I am only getting NULL.
window.onload = function () {
var Input = document.querySelector('input#Input');
var InputButton = document.querySelector('button.formBtn');
InputButton.onclick = function () {
var InputRequest = new XMLHttpRequest();
InputRequest.open("POST", "ajax.php", true);
InputRequest.send();
InputRequest.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(InputRequest.response)
console.log(obj);
}
}
return false;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Example</title>
<style>
#Input {
width: 200px;
height: 15px;
padding: 10px 0;
text-indent: 5px;
}
#Input:focus {
outline: none;
border: 1px solid lightblue;
}
</style>
</head>
<body>
<form name="form" action="ajax.php" method="post">
<input type="text" id="Input" name="inputTest">
<button type="submit" class="formBtn">Absenden</button>
</form>
<script src="ajax.js"></script>
</body>
</html>
<?php
$inputResponse = $_POST["inputTest"];
echo json_encode($inputResponse)
?>
You are missing a line and need to modify your send() line for sending POST content:
// You need to send the type
InputRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the post values in the send
InputRequest.send('key=value&key2=value2');
In the case of the send() you have to turn the keys and values to a query string. I think this is why so many use jQuery, it's done all this for you.
Related
how can i make automatic click per each 4 sec ?
i want that submit button be clicked every 4 sec.
but its not work correctly
my works :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>*BruteForce*</title>
<script src="!Needs/jquery.min.js"></script>
<style>
#form {
margin: 0 auto;
text-align: center;
}
#getHash {
width: 440px;
text-align: center;
}
#length {
text-align: center;
}
#boxContent {
width: 833px;
height: 469px;
border: 1pt solid black;
text-align: left;
margin: 0 auto;
}
</style>
</head>
<body>
<form id="form" method="post" action="server.php">
<span>Enter Your Hash (SHA256) : </span>
<input id="getHash" type="text" value="" name="getHash" title="">
<input id="length" type="number" value="" name="length" placeholder="Enter the Length">
<input id="create" type="submit" value="create" title=""><br><br>
<div id="boxContent"></div>
<input id="btn" type="button" value="..." title=""><br><br>
</form>
<script>
setInterval(function () {
$("#create").click(function () {
event.preventDefault();
$("#boxContent").html(("Loading ..."));
$.ajax({
type: 'POST',
url: "server.php",
data: $("#form").serialize(),
success: function (response) {
$("#boxContent").html((response));
}
});
});
}, 4000);
</script>
</body>
</html>
as you can see . im trying to make simple brutforce method
but its manual , i want to create a auto .
i used setinterval for every 4 sec . but it doesnt work . ? any idea?
Instead of creating click events every 4s, trigger it!
Use that event argument!
PS: if you haven't already (not present in your code above...) You need to include also the jQuery library! <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
const $create = $("#create"); // Cache your elements!
$create.on("click", function (event) {
event.preventDefault(); // Use the `event` argument
// ... other code here
});
setInterval(() => {
$create.trigger("click");
}, 4000);
add jquery library script before your script ex:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
and try this it works for me:
setInterval(() => {
$create.click();
}, 4000);
Execute the same code that the button will execute every 4 seconds and if you want, change the button's style to look like i'ts clicked
I have written a javascript function inside script tag of html file...
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll"></div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
<script type="text/javascript">
// set the focus to the input box
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}
function verify(arguments){
}
</script>
</body>
</html>
i need to move the function verify(arguments) to an external js file.i have to move that because i am calling a nodejs child process which requires a module to be included.
How can i move the function to a external js file and subsequently call verify function from html file.
Make three files as such. It will solve your issue.
index.html
<!DOCTYPE html>
<html>
<head>
<title> Sample Application </title>
<!-- insert these two lines -->
<script type="text/javascript" src="verify.js" ></script>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
<h1 style="text-align: left">Test</h1>
<div id="conversation" style="width: 600px; height: 400px; border: 1px solid #ccc; background-color: #eee; padding: 4px; overflow: scroll">
</div>
<form id="chatform" style="margin-top: 10px" onsubmit="return pushChat();">
<input type="text" id="wisdom" size="80" value="" placeholder="Type your issue">
</form>
</body>
</html>
verify.js
function verify() {
}
other.js
document.getElementById("wisdom").focus();
function pushChat() {
// if there is text to be sent...
var wisdomText = document.getElementById('wisdom');
if (wisdomText && wisdomText.value && wisdomText.value.trim().length > 0) {
// disable input to show we're sending it
var wisdom = wisdomText.value.trim();
wisdomText.value = '';
wisdomText.locked = false;
showRequest(wisdom);
// send it to the Lex runtime
botaction(wisdom);
}
// we always cancel form submission
return false;
}
function botaction(action){
console.log("action: " + JSON.stringify(action));
switch (action.intentName) {
case "details":
var Id = action.userid;
var arguments = [Id];
verify(arguments);
break;
default:
console.log('No action found.');
console.log('executing the default action based on response');
break;
}
}
You can just copy paste the function to a .js file (ex:verifys.js) and include the .js file in the HTML using
I want to send an input type element to a PHP page without form submission, only with javascript. I tried with $.ajax but no way. I don't know if it is a syntax or a logical error. Someone told me to do a single PHP page instead of two.
HTML page: (but is .php)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="../../js/jquery-3.2.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style>
#prova{
padding-right: 1%;
padding-top: 1%;
}
</style>
<script>
function ajax_post(apri){
var stile = "top=10, left=10, width=650, height=600, status=no, menubar=no, toolbar=no scrollbars=no";
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "sperem.php";
var fn = document.getElementById("id_buyers").value;
alert(fn);
var vars = "postid="+fn;
alert(vars);
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
/*window.open(apri, "", stile);*/
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<div class="container">
<center><h1>Add Orders:</h1></center>
<form class="form-inline" name="ordine">
<div class="form-group" id="prova">
<label for="Buyers">ID_Buyers:</label>
<input type="text" class="form-control" placeholder="Enter IDBUYERS" id="id_buyers">
</div>
<div class="form-group" id="prova">
<input type="submit" id="bottone" value="show" onClick="ajax_post('sperem.php')"/>
</div>
</form>
<br><div id="status"></div>
</div>
</body>
</html>
This is the Php page:
<?php
$dato = $_POST['postid'];
echo($dato);
?>
change this from
input type="submit"
to
input type="button"
then you can get the data what you have given in textbox.
The problem here is the form is submitting when you run it on the browser, as if you want run the ajax you need to run the page with out submitting/reloading.
Hope it helps you.
I am new to this.All i am trying to do is upload a image and send it to server to insert in a database.As a start i am limited to echoing the file name which i will send.But i kept on failing to do so.Getting some noisy or undesirable output which makes no sence.Can't figure out the mistakes in this code.It would be great if someone help me with this problem.Thanks!
html and ajax:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>file upload</title>
<!-- Make sure the path to CKEditor is correct. -->
<style>
#mydiv{
position: relative;
overflow: hidden;
width:80px;
height:30px;
background:crimson;
color:white;
text-align:center;
padding:auto;
border-radius:4px ;
border:1px solid black;
font-size:22px;
}
#files{
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
</style>
</head>
<body>
<form action='file.php' id='myform' method='POST' enctype='multipart/form-data' style='width:80px;height:70px;border:2px solid skyblue;'>
<div id='mydiv'>upload
<input type="file" id="files" name="files" multiple />
</div>
<span id='txtHint'></span>
</form>
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
var formData = new FormData();
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
formData.append('image_name',f,f.name);
var name =f.name;
console.log(name);
if (name='') {
document.getElementById("txtHint").innerHTML ='fill the name field';
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "file2.php", true)
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(formData);
}
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
php file:
echo $_FILES['image_name'];
To retrieve the upload file name just do:
echo $_FILES['image_name']['name']
EDIT : According to the name of your html input
echo $_FILES['files']['name']
What about to use BlueImp ? BlueImp is the best i think, and you can easily include on your projects
https://github.com/blueimp/jQuery-File-Upload
All
<input type ="button" value ="test" onClick="SelectAll(this.form);" />
<script ......>
function SelectAll(form)
{
alert(form);
}
</script>
method 1 produce an alert message 'undefined' while 2 method works fine by displaying form object . I'm very much aware that anchor elements don't have a form property, that references the form , unlike input elements,but is there any alternative way to pass form object using hyperlink or is there any way to style the button to look like an hyperlink
Thanks
Try this...
onClick="SelectAll(getParentForm(this));"
function getParentForm(el) {
while(el = el.parentNode) {
if(el.tagName.toLowerCase() === "form")
return el;
}
return null;
}
Since the anchor is not a form control, it doesn't have a form property. You would need to find some other way to reference the form (or stick to a button, which is the right choice of control for something like this).
Honestly? I think your best approach is to not use an anchor element at all. It's not really a link, so that's actually a misuse of HTML.
Use a button element instead, which does have a form property. If you really want it to look like a link, slap on a little CSS to make it look like one.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
button.link {
border: none;
background-color: transparent;
color: blue;
margin: 0;
padding: 0;
cursor: pointer;
text-decoration: underline;
}
</style>
<script type="text/javascript">
function SelectAll( f )
{
alert( f );
}
</script>
</head>
<body>
<form id="test">
<button class="link" onclick="SelectAll(this.form)">All</button>
</form>
</body>
But there are probably a dozen other ways to get a reference to the form element itself. If your form definition looked like this
<form id="test" name="tester">
and it's the only form on the page, here are some ways to obtain a reference to it
document.forms.tester
document.forms['tester']
document.forms[0]
document.getElementById( 'test' )