Sending query string parameters to php via fetch not working [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I simply want to send a query string parameter to a (same page) php script via the fetch api. The purpose is so that I can store a variable that exists in javascript inside a php $_SESSION variable instead. But it's not working.
Background: I wrote some javascript that detected which radio button out of several was toggled on. The value of this radio button stores the name of a PHP template that I wanted to load as an SSI from a database.
So I don't really want to manipulate the response in javascript, I just want to be able to pass the variable (hardcoded in this example, but intended to come from a javascript variable) to PHP $_GET or $_POST.
Thanks to people who have answered so far.
Code below:
<?php
if(isset ($_REQUEST['name'])){
echo "The name param is received!";
}
else {
echo "The name param is NOT received!";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<script>
fetch('index.php?name=matt');
</script>
</body>
</html>

I recommend you take a look at the MDN Fetch() API documentation. Your fetch() is missing its headers, its method, a response resolution (first .then()), and a result resolution (second .then()).
But, you MIGHT NOT WANT to use fetch(). Fetch returns the result of the page to the JavaScript, not to the user. The way you're using it, it looks like you just want the user to go to that page directly (in which case, just <a href='?name=matt'>Click Me</a>).
Ultimately, I think you need to understand that the purpose of fetch() is to send data to the JS environment, not to reload the page for the user. Anyway, here's how your call would look if it worked...
<script>
fetch('index.php?name=matt', {
'headers': {
'Accept': 'text/html',
'Content-Type': 'text/html'
},
'method':'GET',
'body':'',
})
.then((response) => response.text())
.then((responseText)=>{
console.info("Response?");
console.info(responseText); // result: "The name param is received!...(and the rest of your page)
});
</script>
If you wanted to have fetch() return $_GET and/or $_POST variables to the JS in a usable fashion, then welcome JSON and json_encode() into your heart.
Make a new PHP script, userdata.php, and code it as so...
<?php
header('Content-Type: application/json'); // send JSON header, let page know it's JSON
print(json_encode(['name':$_POST['name']])); // get the name
?>
With this, update your above JS to be...
fetch('http://www.example.com/your/script.php', {
'headers': {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'method':'POST',
'body':JSON.stringify({'name':'matt'}),
})
.then((response) => response.json())
.then((responseJson)=>{
console.info("Response?");
console.info(responseJson);
});
Notice what I have changed above: I made it use the POST method, which gives you a cleaner way of sending the data (namely using body, instead of appending it onto the URL, like '?...'). Your response, also, is .json()'d, and not .text()d.

Related

Display the html returned by fetch()

I am using a web app to submit some form data to an API. The process is as follows:
Enter data in a html form
When the user presses a button I use javascript to collect the form data and create a JSON string out of it
Using fetch() I post that JSON to an API endpoint
The API server returns a redirect to a new page (complete html document)
What I would like to achieve is that when the fetch request completes the user would be redirected to the page that was received from the API server. I tried searching for this however I couldn't find anything since most examples are for storing the response in a variable and doing something with it.
This needs to be done in vanilla Javascript, since it is an embedded system and I would like to use as little dependencies as possible.
May be this will work for you.
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<h1>site</h1>
<script>
document.addEventListener("DOMContentLoaded", async () => {
const res = await fetch('/index2.html');
const text = await res.text();
document.open();
document.write(text);
document.close();
});
</script>
</body>
</html>
The answer from Alexander works, however as Nikola already said it's not really considered good practice to clear current html and replace it.
At the end I opted for a different approach. I collected all the data from the original form, created a json string out of it and then dynamically created another form with only one field to which I assigned the value of json string and then submitted this new form. This way I could achieve the redirect behavior of the element while making minimum modifications on the server side.

Unable to find why base64 image code is invalid

Can anyone tell me why the base64 image code linked in here is invalid? Some kind of issue with the syntax I believe?
My file looks like this:
/9j/4AAQSkZJR..........39b/lRk5HGVz8
I have truncated it (the "...") since the entirety of the file won't fit in the question.
Here is my Javascript Fetch API POST code:
function submitPhoto(){
console.log("name: "+name);
console.log("email: "+email);
console.log("market: "+market);
//console.log("base64: "+b64data);
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
Yes I believe the syntax is not correct and it may not be a valid image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KX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==">
the format should likely began with this: data:image/gif;base64, or just this image/gif;base64, so first section shows image type. in your case it should be image/jpeg and the ;base64, is like defining that its a base64 inline image.
And at the end of the code or just end of anybase64 coded content there should be like == or = but you should not remove it its part of the coded content.
So this is another answer. I post it separately, cause your question is changed.
There is two way to achieve this. First is to use URL-encode and URL-decode. So before you send the base64 string containing your image data u do encode it then on the server side you first echo is to see how it looks. Then you use PHP urldecode to get your string back.
URL decode/encode with javascript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
URL decode/encode in PHP:
http://php.net/manual/en/function.urlencode.php
https://stackoverflow.com/a/4744917/9453736
But the other way which should fit better in this situation is to use the post body when u wanna post something. But as you are already using a library to do that I guess its just the limitation of your library. So try to check if there are other ways to set parameters for POST with that library. Like you are adding the parameters to body but the way you do it (the library) just limits you. so for example you cant use some characters when you do this:
{
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
{
So in case you failed to find other ways to do the request. Like you can do it with form object with pure javascript and other ways. so in case you failed just go with the first one try to url encode the data.
example of url encode in javascript:
// encodes characters such as ?,=,/,&,:
console.log(encodeURIComponent('?x=шеллы'));
// expected output: "%3Fx%3D%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"
console.log(encodeURIComponent('?x=test'));
// expected output: "%3Fx%3Dtest"
example of urldecode in PHP:
$query = "my=apples&are=green+and+red";
foreach (explode('&', $query) as $chunk) {
$param = explode("=", $chunk);
if ($param) {
printf("La valeur du paramètre \"%s\" est \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
}
}

How to call php function from JavaScript using Ajax?

In my Wordpress site, I want to create a dropdown menu with all the tags, but since it has more then 7.000, it needs to load only after the user click. I now it is only possible using Ajax, and I have started, but not accomplished yet.
http://jsfiddle.net/7kf1r9vw/2/
In this Fiddle, after the click, this javascript file is loaded:
/echo/js/?js=hello%20world!.
The second example in Fiddle is just to show my actual code. I want that the results populated by the php funcion only starts after the user click.
But I don't know how to change it to a PHP function. Also, is it possible to add plain PHP script in the output or only with it embedded in a file?
As Draco18s said, in your case, Javascript is executed client-side and PHP is executed server side.
In this case what you can do is a request to the server using Ajax.
For example, if you have the following html:
<select name="tag-dropdown" id="selectTags">
<option value="#">Select an artist</option>
</select>
You can use Ajax to make a POST request to a PHP script:
$( document ).ready(function() {
$.ajax({ url: 'merge2.php',
data: {operationName: "tagsNames"},
type: 'post',
success: function(output) {
tagNamesres = JSON.parse(output);
jQuery.each(tagNamesres, function(name, val) {
$("#selectTags").append('<option value="'+val+'">'+name+'</option>');
});
}
});
});
The PHP script can contain something like:
<?php
if (isset($_POST['operationName']) && !empty($_POST['operationName']) && $_POST["operationName"]=="tagsNames") {
$resultarray = array();
$resultarray["tagName1"] = "tagValue";
$resultarray["tagName2"] = "tagValue2";
echo json_encode($resultarray);
return;
}
?>
In order to return something from the PHP function you need to print or use echo.
This is just an example so you could start working with this :)
For more information about how Ajax request works, read this http://thisinterestsme.com/simple-ajax-request-example-jquery-php/
Your question appears to be "how do I call a php function on the server from my browser javascript code". In your code, you have the following function where the first parameter is the server side request:
function getSuccessOutput() {
getRequest(
'/echo/js/?js=hello%20world!', // demo-only URL
drawOutput,
);
return false;
}
To change that to call a server php routine, you would change '/echo/js/?js=hello%20world!' to the url on your server you want to have executed: e.g. '/myPHPFolder/someRoutine.php' . The results will be delivered back to your req object.
In your initial html file (e.g. index.html, or where ever you start your flow), include the onload option on the body tag:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="yada yada yada">
<meta name="author" content="you">
<title>title for browser tab</title>
</head>
<body class="tutorial" onLoad="initPage()">
<select id="optionList"></select>
</body>
</html>
This tells the browser to run the "initPage()" function with no parameters. The initPage() function then issues an async call and loads up your data, perhaps saving it to a local variable in the process.
function initPage()
{
$('#optionList').empty(); // this ensures that you don't duplicate the info in the select list.
$.when($.get('/myPHPFolder/someRoutine.php').done(function(res)
{ // if of interest, save the results to a cookie or variable.
// you could also include a check to see if the data has already been downloaded.
// This is a 'happy path' example, which does not include error checking from the host
// build the optionList select HTML element
for (let each in res)
{(function(_idx, _arr)
{
// append the correct value to the select list.
// this example is based on returning a JSON object with an
// element called "id" which has the value I want to display in the options list
$('#optionList').append('<option value="'+_arr[_idx].id+'">' +_arr[_idx].id+'</option>');})(each, res);
}
// create a function to execute when the user selects a different buyer
$('#buyer').on('change', function() { /* do something useful here */ });
}
}

How to pass data from JavaScript to PHP and then on to MySQL [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax

Protecting against XSS with dynamically generated JavaScript

I have to pass a jQuery plugin some data. I could either pass it a URL where it will use a GET request to fetch the data, or directly pass it an array which will eliminate one server request. The data in question is user provided and not sanitized upon database entry.
The below script doesn't show the plugin, but does show how I might pass the data to the client so it may be directly passed to the plugin. As seen, the dynamically generated JS approach is suspect to XSS, however, the Ajax/JSON approach doesn't seem to be.
For this scenario, how should the dynamically generated JavaScript approach be secured, and is there risk to the Ajax/JSON approach?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>XSS Testing</title>
<script src="getStuff.php?type=js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
console.log(stuff);
$.get( "getStuff.php", function( data ) {
console.log(data);
},'json');
});
</script>
</head>
<body>
</body>
</html>
getStuff.php
<?php
$getFromDB=array(
'Mary',
'x"];alert(\'xss2\');x=["x',
'John'
);
if(isset($_GET['type']) && $_GET['type']=='js') {
header('Content-Type: application/javascript;');
$s='var stuff=[';
foreach($getFromDB as $row) {
$s.='"'.$row.'",';
}
$s=substr($s, 0, -1).'];';
echo($s);
}
else {
header('Content-Type: application/json;');
echo(json_encode($getFromDB));
}
?>
if you expect to work with JSON, why not first and foremost verify that's what you're working with?
$.get(...)
.success(function(data) {
try {
JSON.parse(data)
} catch (e) {
console.error("this isn't actually JSON");
}
})
JSON cannot contain functions, nor function calls, so just asking the browser to see if it can be parsed should be enough to make it go "there is stuff in here that isn't real JSON data".
The same goes for your PHP of course. Never build a string if you need a specific serialization. In this case, construct your key/map object the usual PHP way, and then use the built in json_encode function for converting that to a legal JSON serialization, instead.
It's almost like you've designed your example to be susceptible to hacking. You're doing nothing in the "js" case to ensure that the data is output with proper escaping, you're only doing it in the "json" case.
If you're going to include a JavaScript file that's purely data, like this:
<script src="getStuff.php?type=js"></script>
Then getStuff.php needs to ensure what it sends back is properly escaped as data:
<?php
$getFromDB=array(
'Mary',
'x"];alert(\'xss2\');x=["x',
'John'
);
if(isset($_GET['type']) && $_GET['type']=='js') {
header('Content-Type: application/javascript');
echo('var data = ');
echo(json_encode($getFromDB));
echo(';');
}
else {
header('Content-Type: application/json');
echo(json_encode($getFromDB));
}
?>
And boom: No alert.
Side note: You shouldn't have the ; on the end of the Content-Type strings. I've removed them in the above.

Categories

Resources