get post field by JavaScript - javascript

as you know we can get post field by server side language like php,for example in php
$var1 = $_POST['field1']now I wanna know is it possible to get it by JavaScript to?(or any Client Side Language like VBScript)
for example I have page which has got form
<form method = "post" action="test.php">
in test.php I wanna get field by JavaScript,not by php.
Is it possible and how can I do it if it's possible?

You cannot read $_POST data using JavaScript.
When you submit data through the GET method, the generated query string can be read through the location.search object. Another method to "post" data from page 1 to page 2 is by using hashes.
The location object (JavaScript)
location.href = http://example.com/test.php?formElem=value&another=true#hash
location.search = ?formElem=value&another=true
location.hash = #hash
Example (based on the URL at the previous paragraph)
<script>
var $_GET = (function(){
var query_string = location.search.substr(1); //Exclude the first character: `?`
var data = query_string.split(/&+/); //
var $_GET = {};
for(var i=0; i<data.length; i++){
var qs = data.match(/^([^=]+)(?:=(.*))?$/);
$_GET[qs[1]] = qs[2];
}
return $_GET;
})()
alert($_GET["formElem"]); //Alerts "value"
</script>
An alternative method to transmit data from a form to a JavaScript HTML page is by using hashes:
<form action="index.html#someHash" method="get">
<input type="submit" name="someName" value="someValue" />
</form>
After submission, the following page will be requested: index.html?someName=someValue#someHashThe hash is available through the location.hash property.

in your test.php file, echo your post fields as a JSON object.
echo '<script> var data = '. json_encode($_POST).' </script>' ;
It can be accessed as a dictionary in javascript then.
Output in test.php
<script>
var data = { 'field1' : 'value1' , 'field2' : 'value2' } ;
alert(data['field1']);
</script>

Related

Attempting to Post String to PHP dynamically

Using JavaScript only I want to POST a string to php file and redirect to it at the same time, however, my php file is not picking up the information.
JavaScript:
var data = "&id=" + obj.id;
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
form.value = data;
document.body.appendChild(form);
form.submit();
};
redirect("summary.php","POST");
And the PHP code is simply (NO ERROR HERE, JUST FOR CONVENIENCE):
$id = $_POST['id'];
EDIT:
The problem is that the PHP file is not picking up the name "id". There is no problem in the php file or how I structure my data.
You made a small typo. ALthough it is a huge problem. In PHP you create variables using the $ sign.
var data = "id=" + obj.id;//you don't necessarilly need the & as you are only passing one item(value)
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
//form.value = data;//this won't work. form does not have value attribute:
//create input element
var i = document.createElement("input");
i.type = "text";//set type.
i.name = "id";//set name of the input
i.id = "id";
i.value = obj.id;//set value of input
form.appendChild(i);//add this input to the form
document.body.appendChild(form);//add the form to the body
form.submit();//dynamically submit
};
redirect("summary.php","POST");
In your php script, access it like
<?php
error_reporting(E_ALL);//show all errors and notices
$id = $_POST['id'];//you forgot the $ sign
//for debugging, check the post array
print_r($_POST);
?>
EDIT:
Make sure the obj.id is not null
That's not how you pass the data. value is a property of a form's input element, not the form itself.
So remove the line form.value = data; and replace with
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'id';
input.value = obj.id;
form.appendChild(input);
Now you should be able to get $_POST['id'].

how can i use javascript var in scriplets

I am trying to learn jsp. I know a little bit java and I dont know much about html tags so I simple use java codes as much as I can. What I am trying to do there is getting data from variables from text boxes and using them as string.
var text1 =<% request.getParameter("locationId"); %>;
<%
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>
Scriptlet is executed before any data about webpage get sent from server to client. Whatever you want to do you need to send postback to server (with forms or ajax call). I usually use jQuery so my answer will use it but feel free to modify it to use native JS code. First, I would create a page on server called something like createJsonObject, call it from client with $.ajax (type: "POST") and passed my argument as object
{varID: varID}
On server I would place my JSP on that page, read argumants upon page load, execute function and return object with data to client. In .done() I would do something with that data (display them in form, save them in JS variables...).
Hope this helps you out.
Example (Just showing how you can use Ajax with form example)
HTML form:
<form name="formName" method="post" action="">
<input type="text" name="name" id="firstName" value="" />
<input type="text" name="lastName" id="lastName" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
Ajax Post:
$("#update").click(function(e)
{
e.preventDefault();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var dataObject = {};
dataObject.firstName = firstName;
dataObject.lastName = lastName;
$.ajax({
type:'POST',
data:dataObject,
url:'returnData.php',
success:function(data)
{
alert(data);
}
});
});
PHP:
<?php
$receivedObject = json_decode($_POST['data'], true);
$name = $receivedObject['firstName'];
$lastName = $receivedObject['lastName'];
echo $name . ' ' . $lastName;
?>
I've not test this, so there might be somewhere i've gone wrong. But try something like my example and just ask if you need any help.
Ali, you can not use a javascript variable into jsp scriplate.
<%
String locationId=request.getParameter("locationId");
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>
but vise versa is possible you can use JSP variable into you javascript code.like this.
<script>
var locationId='<%=request.getParameter("locationId")%>';
alert(locationId);
</script>

How to read all text files in a folder and filter display based on the suffix or prefix

I'm trying to use jQuery to read all text files in a folder and display their contents, but then, filter which should ones should be displayed based on the name of the folder.
Here's the JavaScript:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt": "",
"01600610/9874565214_789545623.txt": ""
};
$.each( obj, function(SavedText) {
$.get(SavedText, function(data){
$('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ data +'</div>')
}, 'text');
});
On this:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt":"",
"01600610/9874565214_789545623.txt":""
};
Q1: How do I get all text files inside a folder instead of specifying the file I want?
Q2: How can I filter? For example, how can I only get files ending or starting with 789545.
When these files are on your local filesystem, you can use the HTML5 Filesystem API.
If the files are located on a server, there is no way listing them from plain (client-side) javascript (maybe except a brute-force method, which shouldn't be considered of course). Then you have to write a server script (in PHP/Node/Perl/Phython/...) which will respond to a ajax request with a file list.
If you are using a server script, you should do the filtering on the server (so the answer depends on the language).
Otherwise you should use Regular Expressions:
var search = new RegExp("789545");
for(var file in obj) {
if(search.test(file))
alert(file+": "+obj[file]);
}
This would search for files with a name containing the pattern 789545
Please create index.php file and add this content to it. Create there a folder called "files" and add your files there
<?php
function contains($haystack, $needle){
if (strpos($haystack,$needle) !== false) {
return true;
}
return false;
}
if(isset($_POST['get_files'])){
$folder = "";
$filter = "";
if(isset($_POST['folder'])){
$folder = $_POST['folder'];
}
if(isset($_POST['filter'])){
$filter = $_POST['filter'];
}
$files = array();
foreach(glob($folder.'/*.*') as $filename){
if($filter != ""){
if(contains($filename, $filter)){
$files[] = $filename;
}
}else{
$files[] = $filename;
}
}
print_r($files);
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getData(){
jQuery.post('index.php',{
get_files:true,
folder:"files",
filter:""
},function(data){
jQuery('#container').html(data);
});
}
</script>
</head>
<body>
<input type="button" value="Get data" onclick="getData();" />
<div id="container"></div>
</body>
</html>
You can specify different folder, and filename filter in jQuery post request call
U can use regular expressions to filter the filenames. And for getting all files in a folder, U want to run a server side script. I use perl or php, to do this kinda stuff. U can use ajax to post the request and make the server script to return the file contents.
http://perlmeme.org/faqs/file_io/directory_listing.html
This link is just an example to do what u need in perl. And u could possibly do the same with other languages too

PHP and javascript combining variables issue

I have a PHP file where I display a html table (HTML) with data from a mysql table.
<?php
include 'connexion.php';
session_start();
$idfirm = $_REQUEST['idfirm'];
$namefirm = $_REQUEST['namefirm'];
The rows in the table have the
<tr class="clickableRow"...
Then on row click (javascript) I want to be able to call (POST) another PHP file that will display other information based on some info from the table row.
I have difficulties in achieving this.
What I have done so far is:
echo '
...
jQuery(document).ready(function($) {
$(".clickableRow").click(function() {
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();
// So I can access the field data either like this
var myID = $.trim(tableData[0]);
// or like this:
var name = $(this).closest(\'tr\').find(\'td:eq(1)\').text();
alert(myID);';
echo" // here I would need to access some variables that I received above in PHP from POST
var namefirmx = '{$namefirm}';
var idfirmx = '{$idfirm}';
";
// and here I would like to call another PHP file (with POST) that will display info about the employee
So, how can I make a POST to another php file and send POST variables:name,namefirmx, idfirmx,myID
I am not sure how to make the POST.
I believe there is no other way to call the POST but javascript. (Remember that the POST must be made on row click)
Please help me out here...
Quick example of php script, some html tags are missed, but I think you will get a picture:
<?php
print_r($_POST);
?>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function($) {
$(".clickableRow").click(function() {
$(this).find("form").submit();
});
});
</script>
<table border="1">
<tr class="clickableRow">
<td>
<form method="post"><input type="hidden" name="p1" value="v1"><input type="hidden" name="p2" value="v2"></form>
v1
</td>
<td>v2</td>
</tr>
</table>
I solved my problem using a SO previous question. I am not sure what to do with this question.
Anyway, the answer is: adding a function in javascript, and calling it with my variables.
The function is:
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
You can always add php variables inside your js code like the following :
<?php
$x="ABC";
?>
<script language="javascript">
jsX="<?php echo $x;?>";
alert(jsX);
</script>

How to check output of a created URL?

I want to make a RuneScape(an MMORPG Game) Name Checker. For this i am using an IRC bot. The URL i am using to check names is this- http://rscript.org/lookup.php?type=namecheck&name=
I am using javascript to take input and go to this url for checking names. The code i am using is this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
}
</script>
</head>
<body>
<input class="textBox" id="uname" type="text" maxlength="15" required/>
<input type="button" onclick="nameCheck()" value="Submit">
</body>
</html>
To proceed with this i need a code that could check the output of the final url created ie.
curl. If the output page looks like this:
START
NAMECHECK: NOTAVALIBLE
SUGGESTIONS: blah blah blah
END
Then the code should run the function nameNotAva(). And if the output is like this:
START
NAMECHECK: AVALIBLE
END
Then the code should run the function nameAva().
The question:
I just want that using javascript the output be evalutaled to check that if NAMECHECK: NOTAVAILABLE is a part of the output page or not. If yes then a function nameNotAva() should be run. Otherwise a function nameAva() should be run.
Dont know what language u are using, with jQuery u can do following things
You can load the response inside a div.
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
var output = $('#someDiv').load( curl ).html() // .html() will give you the output or what the page
if( output.contains('NAMECHECK: NOTAVALIBLE'){ nameNotAva(); }
}
You can use simple AJAX and get the response text ( may be with async false)
function nameCheck()
{
var username = document.getElementById('uname').value;
var url = "http://rscript.org/lookup.php?type=namecheck&name=";
var curl = url + username;
$.ajax({
url : curl,
type : 'GET' //or 'POST',
success : function( urlOutput ){
if( urlOutput .contains('NAMECHECK: NOTAVALIBLE'){
nameNotAva();
}
}
});
}

Categories