Reputation: 129
I have the following ajax function:
var data=event.target.result;
var fileName=encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName,"data":data},
success: function(data){
console.log(data);
}
});
the server-side code
<?php
$fileName=$_POST["fileName"];
$data=$_POST["data"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;
echo $data;
In the console.log(data) i'm obtaining the correct results (filename and data) what I want is to have each info alone to use later. that is fileName in a variable and data in another variable in the success function so that I can use them later in the program.I think I should use maybe localstorage and json.stringify??is that correct.or is there another way.and if that is true can you help me how to use localstorage here? thank you in advance
Upvotes: 0
Views: 74
Reputation: 1545
You can put the info in an object or an associative array an then use json_encode, that converts the object in a serialized string. Then you can parse the JSON string in Javascript:
In php, if you have an object or assocciative array, you will write:
echo json_encode($yourObjectOrArray);
Supose data is the data you receive in the success function:
var data = '{"fileName":"yourFileName","data": "yourData", "moreData" : "moreData"}';
var obj = JSON.parse(json);
Upvotes: 0
Reputation: 2815
Try this
var data=event.target.result;
var fileName=encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName,"data":data},
dataType: 'json', //<==== Add this
success: function(data){
console.log(data.filename);
console.log(data.data);
}
});
and you php should be:
<?php
$fileName=$_POST["fileName"];
$data=$_POST["data"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
$data = array('filename'=>$filename, 'data'=>$data);
echo json_encode($data);
?>
Upvotes: 1
Reputation: 3994
You should use JSON in javascript part to have it as an object.
You can use var jsonData = JSON.parse(data.data)
On the server you should encode it in json with the corresponding PHP function: json_encode(YOUR_ARRAY)
More information here: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/JSON/parse
There is a great example here: http://www.caveofprogramming.com/frontpage/articles/php/php-json-an-example-javascript-json-client-with-php-server/
Upvotes: 0
Reputation: 6565
try
php
$result = array("filename" => $fileName, "data" => $data);
echo json_encode($result);
jquery
success: function(response){
console.log(response);
// var myObject = $.parseJSON(response)
// here you have an object with all values now
}
myObject is needed, depending on if you use dataType: "JSON"
in your ajax or not.
Upvotes: 0