jquery ajax variable to php - php

I'm stuck since 2 weeks, since i decided to use a nice threeview based on the jquery library.
My problem is what i'm trying to get the value of an selected folder as an variable to php.
I'm able to get the value and show it via an Alertbox in Jquery but the value is not posted to the PHP variable. echo shows nothing.
Text under is just to clarify why i need to use this solution with php and so on.
Then this is solved i will keep on struggling to get the whole path that i later will send to a bash script what is already finished. It creates a text file with metatags from an flac or mp3 album for my SQL db already done and working. This app is local for maintainance of the database.
To my problem and code (bear in min what jquery and ajax is totally new for my)
filename: file_browser.php
Jquery part
<script>
$(document).ready(function()
{
$("button").click(function()
{
var dir = ($(".active").text())
$.ajax({
type: "POST",
url:"file_browser.php",
data: dir,
success: function(data){
alert(dir); dir }
});
});
});
</script>
PHP code
<?php
echo "<form>
<button>Append</button>
<div id'japp'>";
if (isset($_POST['dir'])) {
$dir = $_POST['dir']; }
echo $dir;
echo "</div>
</form>";
?>
I will keep on trying, now i at leasthave an chance to get some help to avoid taking one more week on this :).

From the jquery website on $.ajax.
By default, Ajax requests are sent using the GET HTTP method. If the
POST method is required, the method can be specified by setting a
value for the type option. This option affects how the contents of the
data option are sent to the server. POST data will always be
transmitted to the server using UTF-8 charset, per the W3C
XMLHTTPRequest standard.
The data option can contain either a query string of the form
key1=value1&key2=value2, or an object of the form {key1: 'value1',
key2: 'value2'}. If the latter form is used, the data is converted
into a query string using jQuery.param() before it is sent. This
processing can be circumvented by setting processData to false. The
processing might be undesirable if you wish to send an XML object to
the server; in this case, change the contentType option from
application/x-www-form-urlencoded to a more appropriate MIME type.
I'm assuming the value of $(".active").text() is just the value you want to pass without any key paired to it. Format your string in a key/value pairs as shown above and you should be great.

If you need your $_POST array to contain a dir element, you need to send a key - value pair to your script:
var dir = { "dir": $(".active").text() };

You should try this:
<script>
$(document).ready(function()
{
$("button").click(function()
{
// setting a key-value
var dir = { dir: $(".active").text() };
$.ajax({
type: "POST",
url:"file_browser.php",
data: dir,
success: function(data){
alert(dir);} //removed the second 'dir'
});
});
});
</script>

The solution is
{
$("button").click(function()
{
var dir = ($(".active").text()); // from my question (gives name of selected dir)
$.ajax({
type: "POST",
url: "file_browser.php",
data: { dir: "dir" },
success: function(response){ // function(response) was (data)
$('#japp').html(dir); // points to the forms id="japp"
alert(dir); }
});
});
});
Question above solved.
My other mentioned problem
Getting full path instead of just dir. Partly solved.
Gives the hole path as string with dir (wanted) + the dir one more time (not wanted).
It also gives website url i think instead of root (/) (not wanted) + visible path on webpage from filesystem (wanted).
This can be solved with an regex in php but i will first try to make it cleaner by getting only the wanted stuff with this jQuery function.
Left my almost done solution here just to give a hint there to begin if needed.
var dir = ($(".active").parent('li').text());
Thanks for all help and for leading me on the right way #Frank B, #jeroen & #Zim84

Related

php doesn't get data from ajax

What I'm doing is I want to detect which reply button I click and send its index to php.
jQuery:
$(".reply").each(function (index5) {
$(".reply_button").each(function (index_b) {
if(index_b==index5){
$(this).on("click",function (e) {
e.preventDefault();
var $this = $(this)
$.ajax({
type:"POST",
url:"/yyqGS/public/form/reply.php",
data:{index:index_b},
dataType: "json",
success:function (d) {
console.log(d);
}
});
})
}
});
});
PHP:
<?php
$n = $_POST['index'];
echo $n+1;
I want to pass the variable index_b to php the file, so that $_POST['index'] can get the value.
But the result on php page is 1, which means it doesn't get the value of index_b from ajax.
On the other hand, what is showed on console is, HOWEVER, correct number! Like, if I click the first reply button, it shows 1, if I click second, it shows 2, and so on...
result on php: always 1.
result on console: correct number.
I couldn't figure out how it happened!
UPDATE:
so i changed console.log() to submit(), i want ajax would send the index to php first, and then another a form will send like 'text' i type to php. But, what's on php page is still 1.
$this.parent() is a form.
So what i really want to do is i want to send the variable index_b to php, and also, at the same time, send those input data to php. So i can use them both.
$(".reply_button").each(function (index_b) {
if(index_b==index5){
$(this).on("click",function (e) {
e.preventDefault();
var $this = $(this)
$.ajax({
type:"POST",
url:"/yyqGS/public/form/reply.php",
data:{index:index_b},
success:function (d) {
$this.parent().submit();
}
});
})
}
});
Your PHP page doesn't store the $_POST value in any way - it receives the data through the ajax request (or other requests that send $_POST['index'] data).
When you go to form.php directly, it doesn't know what value $_POST['index'] has (because it's not set) so it uses zero (0) in the math formula. Thus, always outputs one (1).
If you wanted to be able to quickly test the form.php page directly, you could change $_POST['index'] to $_REQUEST['index'], which allows for POST and GET parameters. Meaning, you could test at form.php?index=17 and get output 18 (same output from your existing ajax).
Granted, that has it's own potential issues, so I'd recommend just continue as is with the knowledge that your code does work.

No response from PHP Script

Absolutely new to PHP and so far it isn't pretty.
Anyway, I'm trying to pass a variable over to a PHP script, do a couple things with it, and pass it back to my Javascipt code.
Here's where I pass it off to PHP:
var src=encodeURIComponent("http://www.someonlinesite.com/file.swf");
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response)
}
});
and here's the script:
<?php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm trying to pass the URL of a .SWF video file over to a small PHP script that will use getImagesize() to figure it's dimensions and pass them back.... but I'm not seeing anything in the response and the alert isn't firing.
What's going wrong?
UPDATE:
I've updated the code with the most recent - according to the advice from some nice SO members. When I hardcode the $src variable and navigate directly to the test.php it echoes everything perfectly. So, it looks like the PHP is working. However, it appears like either the callback is never firing or the PHP file isn't returning the data. In the console there still isn't anything in the response.
You need to concatenate your url string parameter in get():
$.get('test.php?src=' + src, function(data){
alert(data);
});
And also, your src variable begins with a double quote and is closed with a single quote. That will cause issues.
var src="http://www.someonelinesite.com/file.swf";
Also, it's probably a bad idea to do this via $_GET since you are passing a URL. $_POST would be better or encode the URL before you pass it. The current url you are passing right now would look like this in a browser:
http://www.mysite.com/test.php?src=http://www.someonelinesite.com/file.swf
That's not pretty. Using encodeURIComponent(), your whole URL will end up looking like this:
http://www.mysite.com/test.php?src=http%3A%2F%2Fwww.someonelinesite.com%2Ffile.swf
Edit to $.ajax
$.get above would work just fine, but going with the implementation of $.ajax works too:
$.ajax({
url:'test.php',
type: 'GET', //Add the type
dataType:'json',
data: {'src': src}, //Add the data, leave it out the url
success:function(data){
alert(data)
}
});
Try this :
In Jquery :
var src="http://www.someonelinesite.com/file.swf";
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response.size);
}
});
In php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>

How to list all folders on a server with PHP and JavaScript

On my webserver i have several directories with files in them like:
afolder/file.xml
anotherfolder/file.xml
stillanother/file.xml
The files contain information about some locations I want to show on a Map (with openlayers) so I need the files in JS. The problem is that i don't know what the folders are called and how many of them are there , so I need a list of them.
I need something like this:
for each (folder as f)
map.showLocations(f/file.xml)
How could this be done ?
I searched for the solution but all i found was about files and folders on client side.
I am using prototype js and it is possible to use PHP.
If you list your directories in a PHP variable $directories, you can echo to the page something like
echo '<script>var Directories = '.json_encode($directories).';</script>';
now you have inside your page a javascript variables which you can iterate over and do your magic
for (dir in Directories) {
map.showLocations(Directories[dir]/file.xml);
}
Another option is to have an AJAX request to do it for you (I am using jQuery for this example because I don't know prototype bu it should be roughly the same)
$.getJSON('directories.php', function(data) {
$.each(data, function(index, value) {
map.showLocations(value+'/file.xml');
});
});
and your PHP code should be something like this
<?php
*** iterate over the directories and save them into an array ***
echo json_encode($directories);
exit();
?>
I just had to do this about 2 hours ago for my job. I used a jQuery plugin from A Beautiful Site called jQuery File Tree.
If you're just looking to get the data into JavaScript, then this UI plugin may be overkill, but it contains the source code that will return JSON containing a list of paths, which you can get by calling a jQuery.ajax request.
JavaScript (jQuery):
$.ajax({
type: "POST",
data: {
dir : '/your_directory'
}
contentType: "application/json; charset=utf-8",
url: 'getDirectories.php',
success: function(d) {
//do something with the data
console.dir(d.directories); //d.directories will be an array of strings
}
});
PHP
//return a JSON object with directories
Here is the PrototypeJS version of what everyone else is talking about
new Ajax.Request('getdirectories.php',{
method : 'post',
onSuccess : function(result){
//result.responseJSON is the JSON object
var dirs = result.responseJSON;
dirs.each(function(item){
map.showLocations(item+'/file.xml');
});
});

What is correct way to pass data through .ajax() to a PHP script?

I'm attempting to send a piece of data through jQuery .ajax() to a PHP script which will then be loaded into a div container. The PHP script will then run with this piece of data and its contents will be returned into the aforementioned div container.
Initially, I wrote this piece of code (shown below) which successfully added the correct elements upon a click but wasn't able to name them correctly because it didn't doesn't pass the count_bucket variable to the PHP.
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP));
return false;
});
I then altered the code to this (shown below) in attempt to pass the count_bucket variable to the PHP script.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.ajax ({
type: "GET",
url: "create_new_bucket.php",
data: var count_bucket,
dataType: "json",
async: false,
}).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
The PHP file create_new_bucket.php looks like this:
<?php
include_once "test_functions.php"; // include functions page
$i = $_GET["count_bucket"];
drawBunchNew($i);
?>
I'm unclear which aspect of the .ajax() is incorrect. I suspect I'm not collecting the variable correctly in the PHP or I'm using the incorrect syntax to pass it to the PHP file. If anyone could help me identify the error, I would greatly appreciate it.
*UPDATE******
Thanks Tejs & Tandu. I'm clear on how to structure the data now but I still am having trouble getting the whole bit of jQuery to work. I took Tandu's suggestion to use .load() instead and have changed my PHP to use POST to pull the data but it's still not working correctly.
var count_bucket = 4;
$(".add_bucket").click(function () {
count_bucket++;
var bucket_add = $.load ("create_new_bucket.php", {count_bucket: count_bucket}, }).responseText;
$('#tree_container2').append( $('<div id="bunch' + count_bucket + '">').load(bucket_add));
});
And the PHP is:
<?php
include_once "test_functions.php"; // include functions page
$i = $_POST["count_bucket"];
drawBunchNew($i);
?>
Final working jquery I used (final PHP is same as above):
var count_bucket = 4;
var loadPHP = "create_new_bucket.php";
$(".add_bucket").click(function(){
count_bucket++;
$("#tree_container2").append( $('<div id="bunch' + count_bucket + '">').load(loadPHP, {count_bucket: count_bucket}));
return false;
});
The data property of the ajax request is going to be an object; think of it like JSON:
{ data: var response }
Is not valid JSON. However, you can do something like this:
data: { myKey: 'myValue', myKey2: 'myValue2' }
Or in your situation:
data: { count_bucket: 4 }
And it will send the data contained in the data property to your server as part of that name value set.
Data for ajax in jQuery needs to be passed as a query-string formatted string ('key[]=value&key[]=value&key[]=value') or as a json object ({key: [value, value, value]}). I believe that the var you have there will be a syntax error. You also need to specify the key, so either data: {count_bucket: count_bucket} or data: 'count_bucket=' + count_bucket should do.
Note that it is not necessary to use .ajax(). It's usually a bit nicer to use .load(), .post(), and .get(). In your case, .load() should work fine. Pass the data as the second argument.
Why do you not want the request to be asynchronous? Note that dataType is the data type of the return value, not of what you are sending. Are you receiving json? jQuery can also usually guess this correctly, and if you set the header on the php side, it helps a lot. The GET type is also the default.
Final note: when using .load(), if you pass the data as a string it will use GET, but if you pass it as an object it uses POST.

Using jQuery to store basic text string in mySQL base?

Could someone point me in the right direction here?
Basically, I've got this jQuery code snippet:
$('.bggallery_images').click(function () {
var newBG = "url('" + $(this).attr('src');
var fullpath = $(this).attr('src');
var filename = fullpath.replace('img/Bakgrunner/', '');
$('#wrapper').css('background-image', newBG);
// Lagre til SQL
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: filename,
dataType: 'Text',
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
});
This is being run when I click a certain button. So it's actually within a click handler.
If I understand this correctly, this snippet takes the source if the image I just clicked and strips it so I end up with only the filename. If I do an alert(filename), I get the filename only. So this is working ok.
But then, it does an ajax call to a php file called "save_to_db.php" and sends data: filename. This is correct right? Then, it does a callback which does an alert + data.
Does this seem correct so far?
Cause my php file looks like this:
<?php
require("dbconnect2.php");
$uploadstring = $_POST['filename'];
$sessionid = $_SESSION['id'];
echo ($sessionid);
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
When I click the image, the jQuery snippet fires and I get the results of this php file as output for the alert box. I think that the variables somehow are empty.
Because notice the echo($sessionid); which is a variable I've created just to test what the session ID is. And it returns nothing. What could be the issue here?
Edit: I just tried to echo out the $uploadstring variable as well and it also returns nothing. It's like the jQuery snippet doesn't even pass the variable on to the php file?
You're trying to send just the filename, but you're retrieving a named form field in your PHP code. So you need to send a named form field:
Change your ajax call like this:
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: {filename: filename}, // <= Change #1 (give jQuery a simple object)
dataType: 'text', // <= Change #2 ('text', not 'Text')
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
Your PHP script will now receive a POST varible called filename whose value comes from your filename Javascript variable. (You can also use $.post to do this, but it's just a wrapper for ajax anyway...)
Passing a simple object into the ajax call is the easiest way to send fields to the server. jQuery will take the object and create the URL-encoded form data (doing all of the escaping for you) by using the object's keys and field names. So for instance, if you give it this object:
data: {a: 1, b: "testing one two three", c: 3}
...it sends this URL-encoded data:
a=1&b=testing+one+two+three&c=3
(Note how it encodes it for us.) More in the ajax docs (but beware, at present what the docs say about array handling is wrong; see this bug report for details).

Categories