value not defined when access php with get method from javascript - javascript

I want to send value with get method to my php file.
if i set my url like this
http://example.com?id=13
it can run normally, but when my id is like this
http://example.com?id=a0013
a get error in my console log a0013 is not defined. This is my code
<?php
//set $id value
$id=a001;
?>
<script type='text/javascript'>
function init(){
ja = new google.maps.Data();
ja.loadGeoJson('example.php?id='+<?php echo $id; ?>+'');
}
</script>
my example.php
<?php
$id=$_GET['id'];
//another action
?>

You seem to be confusing PHP and JavaScript;
PHP is a server side scripting language
JavaScript is a client side scripting language
The console you mention, is through a browsers inspector tool, and runs off of JavaScript.
If you want to get a request param from this, you could do the following;
// Remove the "?" from the URL and split this down by the ampersand
var requestParams = window.location.search.replace("?", "").split("&");
for (var i in requestParams)
{
// For each of the request parts, split this by the = to het key and value
// the console log them to display
var _params = requestParams[i].split("=");
console.log("Request Param; " + _params[0] + " = " + _params[1])
}
This will output something such as;
Request Param; id = a0013
You can also use these in PHP;
foreach ($_REQUEST as $key => $value)
{
print "Request Param; {$key} = {$value}<br />";
}
Which will result in the same thing. If you wanted just the a0013 value; using;
print $_REQUEST['id'];
Will give you this.
Trying to target via the a0013 won't work as that is the value in the data, not the key
NB - I use $_REQUEST in this, there is also $_GET (what you see in the URL bar and what JavaScript has access to via window.location.search) and $_POST which is hidden from the user
FOLLOWING OP EDIT
Add quote marks around your $id=a001; to make it $id='a001';
The reason it works with 13 and not a0013 (or a001) is because 13 is an integer and does not need quotes, because the latter has a string (starts with "a") it MUST have quotes around it (single or double, doesn't matter)

Related

How to receive HTTP POST parameters on vue.js? [duplicate]

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

Javascript code does not accept the json encoding send from my php database script

today I have been working on a web application where my javascript sends a get request to a php file which handles database communication and replies with an array encoded in json.
But for some reason when I try to use JSON.parse on the response object of the get request I get
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
From what I have managed to find by googleing around this means that there is something wrong with the json formatting. But I can't seem to be able to determine what is wrong.
.js code
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
alert(this.responseText);
var str = this.responseText;
var total = JSON.parse(str);
alert(total);
alert(total[0]);
};
var id = get('id'); //calls to a different function to retrive the get data
var ar = get('ar');
oReq.open("get", "getdata.php?id=" + id +"&ar=" + ar, true);
oReq.send();
getdata.php
<?php
header('Content-Type: application/json');
require 'connect.php';
if(isset($_GET["id"])){
$id = $_GET["id"];
$ar = $_GET["ar"];
if($stmt = $conn->prepare("SELECT id, nummer, navn, alder, rase, eier, adresse, postnummer, sted, email, tlf FROM hoppe WHERE id = ?")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($unikid, $nummer, $navn, $alder, $rase, $eier, $adresse, $postnummer, $sted, $email, $tlf);
while ($stmt->fetch()) {
$unikid = (string)$unikid;
$data = array($navn,$nummer,$alder,$adresse,$postnummer,$sted,$email,$tlf,$eier,$unikid);
}
$stmt->close();
}
}
echo json_encode($data,JSON_UNESCAPED_UNICODE);
//echo json_encode($data);
?>
Using json_encode without JSON_UNESCAPED_UNICODE makes no difference on the syntax error. If I do not use it, special characters like æøå will be displayed as "\u00e5" or "\u00f8".
The direct output of getdata.php if I access it through a web browser is:
["Leif","456","1970-01-01","Bakken1","4867","Oslo","lf#kgo.com",864654,"Kåre","12"]
If I copy this output and place it directly into my javascript then my JSON.parse will work as expected.
The database connection has a fixed charset to "UTF-8", and the database uses "utf8_general_ci" so I am fairly sure everything should be in the right format. But if I use a site like json formater & validator it gives me an output which indicated otherwise
Error:Invalid encoding, expecting UTF-8, UTF-16 or UTF-32.[Code 29,Structure 0]
Error:Expecting object or array, not string.[Code 1, Structure 1]
Error:Strings should be wrapped in double quotes.[Code 17, Structure 1]
But if I again copy paste the direct output I view in my web browser it confirms it as valid.
So, what am I missing?
EDIT 1:
Found out that the error was caused by my php files not being encoded in UTF-8 without BOM. Hope this helps someone experiencing the same problem.

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

Json_encoding a Php Variable in an Ajax Request

Currently I am using a jQuery Ajax asynchronous function to request a PHP page multiple times until a large number of spreadsheet rows are processed. Right now I am using the following code to set the variables to be passed to the requested page, I am not sure if this is the proper way to do it or not. PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
$new_spreadsheet = json_encode($new_spreadsheet);
echo var_dump($new_spreadsheet);
}
JavaScript/PHP:
var done = false,
offset = 0,
limit = 20,
rankings_abv_twenty = 0,
sum = 0,
num_count = 0,
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
On the requested PHP page (which happens to be Object-Oriented PHP), I have the following code to slice off 20 rows to process on the given request. Please not the PHP is a full working class, I just did not include all the PHP for the sake of post length. Also note, I have another page which calls the class, which passes the spreadsheet variable to the constructor of the PHP by reference as $_POST['spreadsheet'], so I know I have the right value as the spreadsheet. PHP:
$this->offset = $offset;
$this->limit = $limit;
$this->spreadsheet = json_decode($spreadsheet);
Here is the PHP line which slices off the rows:
$this->rows = array_slice($this->spreadsheet, $this->offset, $this->limit);
For some reason my code is not working properly and is giving me the following errors relating to the above code:
PHP Warning: json_decode() expects parameter 1 to be string, array given
PHP Warning: array_slice() expects parameter 1 to be array, null given
I think it might have something to do with how my string is getting passed the requested PHP. Also, just as a further note, when I use var_dump() on my spreadsheet variable before it is passed to the requested PHP, I get it outputted as a string like so:
string(7560) "String content goes here"
On the first look, instead of echoing the json_encode, you used var_dump.
And when manually modifying the json encoded string make sure to use " around the vars.
And this:
websites = 1
<?php if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo ', spreadsheet = '.$new_spreadsheet;
}?>;
Will result in:
websites = 1, spreadsheet = "{"1":"foo","2":"bar","3":"baz","4":"blong"}";
Wrap the line in ' if that's what you expect it..
like this:
echo ", spreadsheet = '".$new_spreadsheet."'";

Categories

Resources