I want to know how I can pass data from my script javascript to my php code to use the data into a query I tried many things but it didn't work for me So this is my script to upload files from input type: file then i get the url in downloadURL variable
var downloadURL;
...
uploadTask.on('state_changed',function(snapshot){
},function(error){
},function(){
downloadURL=uploadTask.snapshot.downloadURL;
alert(downloadURL);
});
Now I want to pass downloadURL to my php so I can use it .
I also tried Ajax to do this task but it didn't work or the code that I used is false
Ajax code :
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
EDIT
Php code :
<?php
$user=$_POST['downloadURL'];
echo $user;
?>
Just a normal echo to test if data is Posted or not
-
What do you mean by didn't work? any errors?Spoody– Spoody2018年04月26日 21:21:30 +00:00Commented Apr 26, 2018 at 21:21
-
When I echo the result it said undefinedAmine Karimi– Amine Karimi2018年04月26日 21:22:28 +00:00Commented Apr 26, 2018 at 21:22
-
You had no url for your ajax request. Give url to ajax request and will workSider Topalov– Sider Topalov2018年04月26日 21:22:45 +00:00Commented Apr 26, 2018 at 21:22
-
Also from your php you should return any value to ajaxSider Topalov– Sider Topalov2018年04月26日 21:23:49 +00:00Commented Apr 26, 2018 at 21:23
-
2Provide your php code and i will help youSider Topalov– Sider Topalov2018年04月26日 21:52:57 +00:00Commented Apr 26, 2018 at 21:52
2 Answers 2
Structure the data of your $.ajax request in a name-value pair manner.
Change this:
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
To this:
$.ajax({
type: "POST",
data: {"downloadURL":downloadURL} ,
success: function(data)
{
//alert(data);
}
});
I also removed url from your $.ajax request because by default url is set to the current page.
With the above modifications, your PHP code will remain unchanged (e.g., $user=$_POST['downloadURL'];).
Comments
Okay change your php with that code:
if(isset($_POST['downloadURL']) {
$response = array(
'user' => $_POST['downloadURL']
);
echo json_decode($response);
exit;
}
Because you are making ajax request you must return json that why we parse our Array to json(object) and then in your javascript ajax request inside success function write
console.log(data);
And after data
...
data: downloadUrl,
Add this
dataType: 'json'
This mean we are telling on our ajax request that we are expecting json response