Convert input textfield to plain text and use it as PHP variable - javascript

I am trying to convert an input textfield to plain text and use it as a PHP variable but I don't know how to do it.
Here's my sample code to convert input to plain text:
HTML
<input type="text" id="fileserver"> <button onclick="disable_all();">SUBMIT</button>
And here's my JavaScript code:
function disable_all(){ $( "body" ).html($( "#fileserver" ).val()); }
Is there any way that I can use the converted text to hold as PHP variable? I hope someone can help me. Thank you so much. :)
FIDDLE FOR REFERENCE

As PHP runs on the server and has finished before the client ( browser ) gets the webpage and because javascript runs in the client ( browser ) you need to send the javascript variable to PHP via some means. You can use a form submission - PHP would process the submitted data but this does mean you leave the current thread. The more common way to send data to the backend is via Ajax or Fetch
The example below sends a simple Ajax request to the same page ( can be any php script not just same page ), does some tasks ( modifies the POST array data here for illustration ) and sends a response which the ajax callback can process.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST'){
/* Allow PHP to process the request, perform whatever tasks it has to do and then send reply */
$_POST['time']=time();
$_POST['date']=date( DATE_ATOM );
$_POST['ip']=$_SERVER['REMOTE_ADDR'];
$_POST['reversed']=strrev( $_POST['fileserver'] );
exit( json_encode( $_POST ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
/* ajax callback - this can do lots more than simply display response in the console. */
const callback=function( r ){
console.info( r )
};
/* ultra simple ajax function to send a POST request to the same page */
const ajax=function(data,callback){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback( this.response )
};
xhr.open( 'POST', location.href, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( data );
};
/* invoke the ajax function when the button is pressed */
const disable_all=function(){
let data={
fileserver:document.querySelector( 'input[ name="fileserver" ]' ).value
};
let payload=Object.keys( data ).map( k=>{
return [ k, data[ k ] ].join('=')
})
ajax( payload, callback );
};
</script>
</head>
<body>
<input type='text' name='fileserver' id='fileserver' value='Open the console to view the result' />
<button onclick='disable_all();'>SUBMIT</button>
</body>
</html>
is this what you mean?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
const convert_to_text=function(e){
let input=document.querySelector( 'input[ name="fileserver" ]' );
let text=document.createTextNode( input.value );
input.replaceWith( text );
};
</script>
</head>
<body>
<input type='text' name='fileserver' id='fileserver' />
<button onclick='convert_to_text()'>Convert</button>
</body>
</html>

Related

How can I POST data from javascript to a c sharp back-end, and then receive it back?

So, I am fairly new to C Sharp and I can't figure out how I can basically submit a POST request via javascript (in the front-end) using fetch, send it to a C Sharp back-end to process the data, and then receive it back to my site.
My final goal is to achieve a search engine, where I can get user input from javascript and send it to my C Sharp back-end so I can crawl sites from a database and return the ones which contain the highest volume of the key-word.
Here is what I am currently working within the front-end:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./index.css">
<title>Search Engine</title>
</head>
<body>
<form class="search">
<h2>Search Engine</h2>
<input name="search" type='text' placeholder='Search' />
<button type="submit">Submit</button>
</form>
<script>
const endpoint = "file to send data to";
const formEl = document.querySelector('form');
formEl.addEventListener('submit', async(e) => {
e.preventDefault();
const formData = new FormData(formEl);
const formDataSerialized = Object.fromEntries(formData);
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(formDataSerialized),
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
console.log(json);
} catch(e) {
console.error(e);
alert('there was an error!');
}
})
</script>
</body>
</html>
As you can see, I have a basic form that submits a user search, however, the endpoint in my javascript function is currently empty, since I am not sending the data anywhere.
I was looking around for a long while for a solution where I can make a web server with C Sharp and accept the data that way, however didn't find anything which I can use.
Can anyone please help? I would appreciate it a lot.

Why is JSON Data Not Inserting Properly

I am trying to render local JSON data to the DOM using the following code, but it's not working. I'm not sure what I am doing wrong and would appreciate any help.
HTML
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="model-controller.js"></script>
</head>
<body>
<button id="clickMe" style="background-color: #000; color: white;" onClick="myObj()">Click ME</button>
</div>
<div id="demo"></div>
</body>
</html>
model-controller.js
var myObj = JSON.parse("item-data.json", function(data) {return data});
document.getElementById("demo").innerHTML = data;
};
myObj();
The JSON.parse function gets a string that represents a json encoded object, and not a path to a file.
If you need to parse a file you can use jquery to access the file
$.getJSON('item-data.json', function(data) {
document.getElementById("demo").innerHTML = data;
});
Or get the content of the file using vanilla javascript and then JSON.parse it:
var request = new XMLHttpRequest();
request.open("GET", "item-data.json", false);
request.send(null)
var json_obj = JSON.parse(request.responseText);
document.getElementById("demo").innerHTML = json_obj;
JSON.parse parses a given string into a JS object. It doesn't load an external file though. See this page for more info on the JSON.parse method
What you want to do is fetch the file with e.g. jQuery.getJSON, jQuery.get or axios.
jQuery.get( 'https://api.coinbase.com/v2/prices/spot?currency=USD', ( data ) => {
$( '#result' ).text( JSON.stringify( data, null, 2 ) );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"></pre>

How to use a .click function in jQuery

The following code should add 100 to an existing number in a mysql table if the button gets clicked. If I click the button nothing happens, but if I reload the page the function adds 100 to the number. What is wrong with my code?
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
<?php
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
?>
});
</script>
</html>
You cant call PHP code from a jQuery function like that. All the php runs when the page loads and thats it. You can however use jQuery and Ajax to send a message to a php script that processes that message then returns a response. The script can even be in the same actual file like you have (or in a different file altogether) something like this would do:
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
if(isset($_POST['updateTest']){
$val = $_POST['test'];
$id + $_POST['userId'];
// validate inputs and such....
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
// send success or error response...
echo json_encode(['success'=>true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
var count = 100;
var userId = 1;
var dataObject= {updateTest: true, test: 100, userId: 1};
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataObject,
success: function(response) {
if(response.success){
alert('test worked');
}
else{
alert('there was an error')
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</html>
As mentioned by the previous poster PHP is server side and Javascript client side so what is actually happening is the following.
When the page is returned back to the user your piece of javascript just looks like the below..
Your MySQL statement here has executed already it can not interact with client side code in this way
<script>
$("#button").click(function(){
// nothing here.. But your MYSQL statement has executed anyway
});
</script>

get element Tag value from the xml

this is my JavaScript code:-
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API with Google Maps API</title>
<meta charset="UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body onload="getlg()">
<script>
function getlg(){
var region = $('#region').val();
var xml;
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/xml?address="+$("#region").html()+"&sensor=true",
async: false,
dataType:'text/xml',
success: function(data){
xml=data;
$('#Div_Get').html('');
}
});
xmlDoc = $.parseXML( xml );
$xml = $( xmlDoc );
var abc= xmlDoc.getElementsByTagName("lat")[1].firstChild.nodeValue;
}
</script>
<div id="region">Rajkot</div>
<div id = "Div_Get"></div>
</body>
</html>
here i am try to set value in url and get the xml file.
now i try to get from this xml lat and long value.
i am try getElementsByTagName but not success nothing is output and give me error xmlDoc is null on this line var abc= xmlDoc.getElementsByTagName("lat")[1].firstChild.nodeValue;
please help me out of this.
thanks.
Change you datatype from
dataType:'text/xml',
To
dataType:'xml',
And Please have a look at documentation for Specifying the Data Type for AJAX Requests.

How to send web browser a loading page, then some time later a results page

I've wasted at least a half day of my company's time searching the Internet for an answer and I'm getting wrapped around the axle here. I can't figure out the difference between all the different technology choices (long polling, ajax streaming, comet, XMPP, etc.) and I can't get a simple hello world example working on my PC.
I am running Apache 2.2 and ActivePerl 5.10.0. JavaScript is completely acceptable for this solution. All I want to do is write a simple Perl CGI script that when accessed, it immediately returns some HTML that tells the user to wait or maybe sends an animated GIF. Then without any user intervention (no mouse clicks or anything) I want the CGI script to at some time later replace the wait message or the animated GIF with the actual results from their query.
I know this is simple stuff and websites do it all the time using JavaScript, but I can't find a single working example that I can cut and paste onto my machine that will work in Perl.
Here is my simple Hello World example that I've compiled from various Internet sources, but it doesn't seem to work. When I refresh this Perl CGI script in my web browser it prints nothing for 5 seconds, then it prints the PLEASE BE PATIENT web page, but not the results web page. So the Ajax XMLHttpRequest stuff obviously isn't working right. What am I doing wrong?
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub Create_HTML {
my $html = <<EOHTML;
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />
<script type="text/javascript" >
var xmlhttp=false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
</script>
<title>Ajax Streaming Connection Demo</title>
</head>
<body>
Some header text.
<p>
<div id="response">PLEASE BE PATIENT</div>
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
print Create_HTML();
sleep(5);
print "<script type=\"text/javascript\">\n";
print "\$('response').innerHTML = 'Here are your results!';\n";
print "</script>\n";
If your process relies on query-string parameters, a simple meta-refresh would suffice. E.g. if they load http://yoursite.com/message?foo=1, then that can output a meta tag like:
<meta http-equiv="refresh" content="0; http://yoursite.com/realquery?foo=1" />
And some HTML that has your "please wait" message. The realquery script would actually execute the query and the HTML output by message will remain on the screen until realquery provides some output.
If the query relies on POST data, then it gets a little more complicated, because you can't redirect a POST. You can, however, output a form with some hidden fields and use Javascript to submit it. For example:
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'form_with_hidden_fields' ).submit();
}
</script>
<form method="POST" action="realquery" id="form_with_hidden_fields">
<input type="hidden" name="foo" value="1" />
...
</form>
Please wait while your query is processed...
If you're interested in an AJAX solution, here's an example using jQuery:
$( '#submit-button' ).click( function() {
// show a "please wait" image
$( '#status-div' ).html( '<img src="please_wait.gif" />' ); // animated gif
// get form values
var formdata = { foo: $( 'input#foo' ).val(),
...
};
// submit form via ajax:
$.ajax( { type: "POST", url: "/realquery", data: formdata, success: function() {
$( '#status-div' ).html( '<img src="success.gif" />' );
} );
} );
And you could attach that to a form like:
<form>
<input type="text" name="foo" id="foo" />
<input type="submit" id="submit-button" />
<div id="status-div"> </div>
</form>
The empty status-div div will receive an image tag that points to a "please wait" image (this can be an animated gif). When the Ajax query finishes, it's replaced by a "success" image.
See Watching long processes through CGI by Randal Schwartz.
Here is a complete working example using friedo's HTTP meta refresh solution. This is not my personal first choice solution because it modifies the URL in the browser and it also refreshes the whole web page.
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub html_page {
my ( $meta_string, $results_string ) = #_;
my $html = <<EOHTML;
<html>
<head>
$meta_string
<title>Two Stage Web Page Demo</title>
</head>
<body>
Some header text.
<p>
$results_string
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
if ($cgi->param()) {
if ($cgi->param('doResults') eq "true") {
sleep(5);
print html_page('', 'Here are your results!');
}
}
else {
my $meta_refresh = '<meta http-equiv="refresh" content="0; /cgi-bin/twoStageScript.pl?doResults=true" />';
print html_page($meta_refresh, 'PLEASE BE PATIENT');
}
exit;
Finally got an Ajax version working. The slow.pl file is the file that takes a while to return.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Two Stage web page demo using Ajax</title>
</head>
<body>
<h1>Two Stage web page demo using Ajax</h1>
<div id="result">
Users input form goes here.
<p>
<input type="submit" value="Here is your submit button" id="load_basic" />
</div>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "Please be patient, this could take a while. <p> <img src='img/load.gif'/>";
// load() function
$("#load_basic").click(function(){
$("#result").html(ajax_load).load("/cgi-bin/slow.pl");
});
</script>
</body>
</html>

Categories