Node.js-Jquery-AJAX

To do anything on the client side check the JQuery library first as it is the easiest way.

https://www.w3schools.com/jquery/jquery_examples.asp

Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside of a browser

jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. Add this script at the beginning of html.

<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
</head>

Node.js lets developers use JavaScript to write Command Line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser. 

Ajax is a part of Jquery.

AJAX means Asynchronous JavaScript And XML.

AJAX applications might use XML, JSON, plain text to transport data.

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)
  • JavaScript and HTML DOM (to display or use the data)

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes.

It is possible to update parts of a web page, without reloading the whole page.

=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-

Simple send string to server

html Browser uses: JQuery Post is the simplest

<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“button”).click(function(){
$.post(“demo_test_post.asp”,
{
name: “Donald Duck”,
city: “Duckburg”
},
function(data,status){
alert(“Data: ” + data + “\nStatus: ” + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>

html Browser uses: AjaxSendS

<!DOCTYPE html>
<html>
<body>

<head>
<meta charset=”utf-8″ />
<title>AjaxSendS.htm</title>
<script src= src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
</head>
<h1>AjaxSendS.htm using XMLHttpRequest Object </h1>
<h3>send a tsring to server programatically and get a response:</h3>

<p id=”AmirResponse”>Response: </p>

<script>

StringToServer();

function StringToServer()

{

var xhttp;
xhttp = new XMLHttpRequest();

//XMLHttpRequest.onreadystatechange property contains the event handler to be called when the //readystatechange event is fired, that is every time the readyState property of the XMLHttpRequest changes.
xhttp.onreadystatechange = function() {

if (this.readyState == 4 && this.status == 200) {
document.getElementById(“AmirResponse”).innerHTML = this.responseText;
}
else
{
document.getElementById(“AmirResponse”).innerHTML = “oops”+this.readyState+this.status;
}

};

$a=”Al”;

// Does not work xhttp.setRequestHeader(“Content-type”, “multipart/form-data”);
// Does not work xhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
// Does not work xhttp.setRequestHeader(“Content-type”, “text/plain”);

// GET And POST both Work This could be GET but I prefer to always use POST
xhttp.open(“POST”, “RecieveSRespondS.php?AmirS=”+$a, true);
xhttp.send();

}

</script>

</body>
</html>

 

xhttp.open(“POST” last logical is asynchronous – True or False?

To send the request asynchronously, the async parameter of the open() method has to be set to true:

xhttp.open(“GET or POST”, “ajax_test.asp”, true);

Sending asynchronous requests is a huge improvement for web developers. Many of the tasks performed on the server are very time consuming. Before AJAX, this operation could cause the application to hang or stop.

 

=-=-=-=-=-=-=-

php on the server:RecieveSRespondS

<?php
#RecieveSRespondS.php
# Array with names
$a[] = “Alireza”;
$a[] = “Niloufar”;

# get the AmirS parameter from URL
$q = $_REQUEST[“AmirS”];

$hint = “”;

# lookup all hints from array if $q is different from “”
if ($q !== “”) {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === “”) {
$hint = $name;
} else {
$hint .= “, $name”;
}
}
}
}

# Output “no suggestion” if no hint was found or output correct values
echo $hint === “” ? “no suggestion” : $hint;
?>

=-=-=-=-=-=-=-

Communicate using Json


<!--HTML File-->
<script type="text/javascript">     
    $(document).ready(function(){
        $(".link").click(function(){
        var aa = $(this).attr('title'); 
          $.ajax({
             url: "Amirdata.php", 
             dataType: "json", 
               data: {"number1": aa}, 
             success: function(json){ 
                $("#result").html(json.number1); 
             }
          });
        });
    });
    </script>
      <a href="#" class="link" title="apple">A</a>
      <a href="#" class="link" title="banana">B</a>
      <a href="#" class="link" title="orange">O</a>
        <div id="result"></div>
<?php
#Amirdata.php on the server
$number1 = $_GET['number1'];
echo json_encode(array('number1' =>$number1));
?>

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

// HTML TO FETCH a file from the server in html client

// This shows the text of textfiles

<DOCTYPE html>
<header>
<title>FileFetch.htm</title>
</header>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>
<button type=”button” onclick=” GetInfo();”>Do</button>
<p id=”demo”></p>
<p id=”pemo”></p>
<input id=”amirfileid” name=”amirfilename” type=”text”>
<div id=”hiddenDiv” hidden></div>
</body>

<script>

// we click on the link to file
function GetInfo()
{

var filetobedoanloaded = document.getElementById(‘amirfileid’);
document.getElementById(‘hiddenDiv’).innerHTML = ‘<a id=”myLink” href=’+filetobedoanloaded.value+’ >Save</a>’;
document.getElementById(“myLink”).click();

}

</script>

</html>

//1) HTML TO FETCH the content of a file from the server in html client next example is easier and uses load method in JQuery

<DOCTYPE html>
<header>
<title>FileContentFetch.htm</title>
</header>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>
<button type=”button” onclick=” GetInfo();”>Do</button>

<input id=”amirfileid” name=”amirfilename” type=”text”>

<p id=”demo”></p>
<p id=”pemo”></p>
<div id=”hiddenDiv” hidden></div>
</body>

<script>

// we will get a response that contains the file content
function GetInfo()
{

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{

if (this.readyState == 4 && this.status == 200)
{
document.getElementById(“pemo”).innerHTML = this.responseText;
}

};

var filetobedoanloaded = document.getElementById(‘amirfileid’);

xhttp.open(“POST”, “ServeMyFile.php?AmirS=”+filetobedoanloaded.value , true);
xhttp.send();
}

</script>

</html>

=-=-=-=-=-

//2) HTML TO downLoad the content of a file from the server in html client

=-=-=-=-=-=-=-=-=-=-

<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“button”).click(function(){
$(“#div1”).load(“demo_test.txt”);
});
});
</script>
</head>
<body>

<div id=”div1″><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Get External Content</button>

</body>
</html>

=-=-=-=-=-=-

On the server side to serve the files under /var/www/html and its subdirectories

<?php
#ServeMyFile.php
# get the AmirS parameter from URL
$file = $_REQUEST[“AmirS”];

if (file_exists($file)) {
echo basename($file);
header(‘Content-Description: File Transfer’);
# header(‘Content-Type: application/octet-stream’);
header(‘Content-Type: multipart/form-data’);
header(‘Content-Disposition: attachment; filename=”‘.basename($file).'”‘);
header(‘Expires: 0’);
header(‘Cache-Control: must-revalidate’);
header(‘Pragma: public’);
header(‘Content-Length: ‘ . filesize($file));
readfile($file);
exit;
}
?>

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
 
=-=-=-=-=-=-=-=-=-=-=-=-=-

File upload

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

//1) This html file sends a file from a form without submit button using Ajax and formData:AmirAjaxupload

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″ />
<title>AmirAjaxUpload.htm</title>
<script src= src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
</head>
<body>

<!–
By default, we assume Ajax uploads are not supported.
Later we’ll detect support and change this message if found.
–>
<p id=”support-notice”>by default Your browser does not support Ajax uploads :-(<br/>The form will be submitted as normal.</p>

<!– The form starts enctype=”multipart/form-data”> is necessary for file transfer–>
<!– Action can be sent to an absolute URL — <form action=”a php in the var/www/html”> –>

<form action=”AmirFileGetter.php” method=”post” enctype=”multipart/form-data” id=”form-id”>

<!– The file to upload –>
<p><input id=”file-id” type=”file” name=”uploaded_file” />

<!–
Also by default, we disable the upload button.
If Ajax uploads are supported we’ll enable it.
–>
<input type=”button” value=”Upload” id=”upload-button-id” disabled=”disabled” /></p>

<!– A different field, just for the sake of the example –>
<p><label>Some other field: <input name=”other-field” type=”text” id=”other-field-id” /></label></p>

<p> readyState:</p>
<p id=”readyState”>initialreadyState</p>
<p> statusText:</p>
<p id=”statusText”>initialstatusText</p>
<p> responsetext:</p>
<p id=”responsetext”>initialresponsetext</p>
<p> reason:</p>
<p id=”reason”>initialreason</p>
<p> completion:</p>
<p id=”completion”>initialcompletion</p>
<!– Placeholders for messages set by event handlers –>
<p id=”upload-status”></p>
<p id=”progress”></p>
<pre id=”result”></pre>

<script>

// Actually confirm support
if (supportAjaxUploadWithProgress()) {
// Ajax uploads are supported!
// Change the support message and enable the upload button
var notice = document.getElementById(‘support-notice’);
var uploadBtn = document.getElementById(‘upload-button-id’);
notice.innerHTML = “amir joon Your browser supports HTML uploads. Go try me! :-)”;
uploadBtn.removeAttribute(‘disabled’);

// Init the single-field file upload
initFileOnlyAjaxUpload();
}

// Function that will allow us to know if Ajax uploads are supported
function supportAjaxUploadWithProgress()

{

return supportFileAPI() && supportAjaxUploadProgressEvents() && supportFormData();

// Is the File API supported?
function supportFileAPI() {
var fi = document.createElement(‘INPUT’);
fi.type = ‘file’;
return ‘files’ in fi;
};

// Are progress events supported?
function supportAjaxUploadProgressEvents() {
var xhr = new XMLHttpRequest();
return !! (xhr && (‘upload’ in xhr) && (‘onprogress’ in xhr.upload));
};

// Is FormData supported?
function supportFormData() {
return !! window.FormData;
}

}

function initFileOnlyAjaxUpload() {
var uploadBtn = document.getElementById(‘upload-button-id’);
document.getElementById(“readyState”).innerHTML=”1″;
uploadBtn.onclick = function (evt) {
var formData = new FormData();
document.getElementById(“readyState”).innerHTML=”11″;
// Since this is the file only, we send it to a specific location
var action = ‘AmirFileGetter.php‘;

// FormData only has the file
var fileInput = document.getElementById(‘file-id’);
var file = fileInput.files[0];
formData.append(‘uploaded_file’, file);
document.getElementById(“statusText”).innerHTML=action;
// Code common to both variants
sendXHRequest(formData, action);
}
}

// Once the FormData instance is ready and we know
// where to send the data, the code is the same
// for both variants of this technique
function sendXHRequest(formData, uri) {
// Get an XMLHttpRequest instance
var xhr = new XMLHttpRequest();

// Set up events
xhr.upload.addEventListener(‘loadstart’, onloadstartHandler, false);
xhr.upload.addEventListener(‘progress’, onprogressHandler, false);
xhr.upload.addEventListener(‘load’, onloadHandler, false);
xhr.addEventListener(‘readystatechange’, onreadystatechangeHandler, false);
document.getElementById(“completion”).innerHTML=”comp”+uri;
// Set up request
xhr.open(‘POST’, uri, true);

// Fire!
xhr.send(formData);
}

// Handle the start of the transmission
function onloadstartHandler(evt) {
var div = document.getElementById(‘upload-status’);
div.innerHTML = ‘Upload started.’;
}

// Handle the end of the transmission
function onloadHandler(evt) {
var div = document.getElementById(‘upload-status’);
div.innerHTML += ‘<‘ + ‘br>File uploaded. Waiting for response.’;
}

// Handle the progress
function onprogressHandler(evt) {
var div = document.getElementById(‘progress’);
var percent = evt.loaded/evt.total*100;
div.innerHTML = ‘Progress: ‘ + percent + ‘%’;
}

// Handle the response from the server
function onreadystatechangeHandler(evt) {
var status, text, readyState;
// alert(“onready try”);
try {

readyState = evt.target.readyState;
text = evt.target.responseText;
status = evt.target.status;
}
catch(e) {
// alert(“onready catch return”);
return;
}
if (readyState == 4 || status == 200)
{
document.getElementById(“readyState”).innerHTML=evt.target.readyState;
document.getElementById(“statusText”).innerHTML=evt.target.statusText;
document.getElementById(“responsetext”).innerHTML = evt.target.responseText;
document.getElementById(“reason”).innerHTML=”4 or 200″;
}
else
{
document.getElementById(“readyState”).innerHTML=evt.target.readyState;
document.getElementById(“statusText”).innerHTML=evt.target.statusText;
document.getElementById(“responsetext”).innerHTML = evt.target.responseText;
document.getElementById(“reason”).innerHTML=”Not 4 or not 200″;
}
if (readyState == 4 && status == ‘200’ && evt.target.responseText) {
var status = document.getElementById(‘upload-status’);
status.innerHTML += ‘<‘ + ‘br>Success!’;

var result = document.getElementById(‘result’);
result.innerHTML = ‘<p>The server saw it as:</p><pre>’ + evt.target.responseText + ‘</pre>’;

}

}
</script>

</form>
</body>
</html>

=-=-=-=-=-=-=-=-=-=-

 

this php recieves the file on linux server:AmirFileGetter

<?php
echo “<p></P>”;
echo “AmirFileGetter.php”;
echo ‘Current script owner: ‘ . get_current_user();
echo “<p></P>”;
#$uploads_dir = ‘uploads/’;
$uploads_dir = ‘/home/amir/Desktop/uploadedfiles/’;

echo $_FILES[“uploaded_file”][“name”];
echo “<p>error:</P>”;
echo $_FILES[“uploaded_file”][“error”];
echo “<p>tmp:</P>”;
echo $_FILES[“uploaded_file”][“tmp_name”];

$tmp_name =”/tmp/” . basename($_FILES[“uploaded_file”][“tmp_name”]);
echo “<p></P>”;
echo $tmp_name;
$name = basename($_FILES[“uploaded_file”][“name”]);
$uploadfile=$uploads_dir . “amir” . $name ;
echo “<p></P>”;
echo $uploadfile;
#this is a php command
echo “<p></P>”;
if (file_exists($tmp_name)) {
echo “The file $tmp_name exists”;
} else {
echo “The file $tmp_name does not exist”;
}
if (move_uploaded_file($tmp_name,$uploadfile )) {
echo “File is valid, and was successfully uploaded.\n”;
echo “<p></P>”;
if (file_exists($uploadfile)) {
echo “The file $uploadfile is safe and sound”;
} else {
echo “The file $uploadfile is not actually uploaded”;
}
} else {
echo “Upload failed”;
echo “</p>”;
echo ‘<pre>’;
echo ‘Here is some more debugging info:’;
print_r($_FILES);
print “</pre>”;

}

?>

=-=-=-=-=-=-=-=-=-=-=-=-

//2) HTML to Upload a file to the server using $.ajax in JQuery

The ajax() method is used to perform an AJAX (asynchronous HTTP) request.

All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

$.ajax({name:value, name:value, … })

https://www.w3schools.com/jquery/ajax_ajax.asp

https://www.w3schools.com/jquery/jquery_ref_ajax.asp

<html>
<head>
    <title>AJAX UPLOAD</title>
    <script type="text/javascript" src="jquery-2.0.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#Button_').click(function(){
                alert("hi");
                var name= document.getElementById('File_');
                 var AmirFileName=name.files[0];
                console.log(AmirFileName.name);
                 var AmirFormData= new FormData();
                 AmirFormData.append('file',AmirFileName);
                 $.ajax({
                 url:'AmirFileGetter.php',
                 data:AmirFormData,
                 processData:false,
                 contentType:false,
                 type:'POST',
                 success:function(msg){
                 alert(msg);
                 }
                 });
            });
        });
    </script>
</head>
<body>
    <input type="file" name="File" id="File_"/>
    <input type="button" name="Button" id="Button_" value="UPLOAD">
</body>
</html>

 AmirFormData.append('file', AmirFileName) in your case is equivalent to <input type="file" name="AmirFileName"> – you passed ‘AmirFileName‘ to append() so ‘AmirFileName‘ is your input name.

You should find your stuff in $_POST['AmirFileName'] and $_FILES['AmirFileName']. Next time try var_dump($_POST); after submit to see the array. 🙂

Learn about file uploads in php here: http://php.net/manual/en/features.file-upload.php

The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.

$_FILES[‘userfile’][‘name’]

The original name of the file on the client machine.

$_FILES[‘userfile’][‘type’]

The mime type of the file, if the browser provided this information. An example would be “image/gif”. This mime type is however not checked on the PHP side and therefore don’t take its value for granted.

$_FILES[‘userfile’][‘size’]

The size, in bytes, of the uploaded file.

$_FILES[‘userfile’][‘tmp_name’]

The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES[‘userfile’][‘error’]

The error code associated with this file upload.

One possible fix would be setting file_uploads = On in the ini file for php.

=-=-=-=-=-=-=-=-=-=

other stuff

=-=-=-=-=

 

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files

index

 is on the server

This html file accessed

<DOCTYPE html>
<html>
<body>

<h1>The XMLHttpRequest Object</h1>
<button type=”button” onclick=”loadDoc(); ;SendMyFile()”>Do</button>
<p id=”demo”></p>
<p id=”pemo”></p>
<input id=”amirfileid” name=”amirfilename” type=”file”>

</body>

<script>

// to send some text
function loadDoc()
{

document.getElementById(“demo”).innerHTML = “in loaddoc”;
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById(“demo”).innerHTML = xhttp.responseText;
}
};
xhttp.open(“POST”, “demo_post2.asp”, true);
xhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xhttp.send(“fname=Amir&lname=Hassan”);

}

 

// to send a file
function SendMyFile()
{

var fileInput = document.getElementById(‘amirfileid’);
var file = fileInput.files[0];
var formData = new FormData(); // FormData interface, Safari 5, Chrome 7 and Firefox 4.
formData.append(‘amirfilename’, file);

}

</script>

</html>

==============================================================================================

//On the server side find your file in $_POST[‘amirfilename’] and $_FILES[‘amirfilename’]
//$uploads_dir = ‘/uploads’;
//foreach ($_FILES[“photo”][“error”] as $key => $error)
//{ if ($error == UPLOAD_ERR_OK)
// {
// $tmp_name = $_FILES[“photo”][“tmp_name”][$key];
// $name = $_FILES[“photo”][“name”][$key];
// move_uploaded_file($tmp_name, “$uploads_dir/$name”);
// }
//}

=-=-=-=-=-=-=-=-

Client side file selection in html with JQuery

<!DOCTYPE html>
<html>
<head>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“:file”).css(“background-color”, “green”);
});
</script>
</head>
<body>

<form action=””>
Name: <input type=”text” name=”user”><br>
File: <input type=”file” name=”myfile”>
</form>

</body>
</html>

 

 

 

 

https://www.w3schools.com/php/php_ajax_php.asp

https://robots.thoughtbot.com/ridiculously-simple-ajax-uploads-with-formdata

=-=-=-=-=-=-=-=-=-=-=-=

jQuery AJAX Methods

The following table lists all the jQuery AJAX methods:

Method Description
$.ajax() Performs an async AJAX request
$.ajaxPrefilter() Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax()
$.ajaxSetup() Sets the default values for future AJAX requests
$.ajaxTransport() Creates an object that handles the actual transmission of Ajax data
$.get() Loads data from a server using an AJAX HTTP GET request
$.getJSON() Loads JSON-encoded data from a server using a HTTP GET request
$.parseJSON() Deprecated in version 3.0, use JSON.parse() instead. Takes a well-formed JSON string and returns the resulting JavaScript value
$.getScript() Loads (and executes) a JavaScript from a server using an AJAX HTTP GET request
$.param() Creates a serialized representation of an array or object (can be used as URL query string for AJAX requests)
$.post() Loads data from a server using an AJAX HTTP POST request
ajaxComplete() Specifies a function to run when the AJAX request completes
ajaxError() Specifies a function to run when the AJAX request completes with an error
ajaxSend() Specifies a function to run before the AJAX request is sent
ajaxStart() Specifies a function to run when the first AJAX request begins
ajaxStop() Specifies a function to run when all AJAX requests have completed
ajaxSuccess() Specifies a function to run when an AJAX request completes successfully
load() Loads data from a server and puts the returned data into the selected element
serialize() Encodes a set of form elements as a string for submission
serializeArray() Encodes a set of form elements as an array of names and values