Get JSON file and push in PHP - javascript

In my data storage folder is a JSON file. I save the device id to the local storage of the broswer:
//Store deviceID in local storage on button click
function store(){
var inputDeviceID= document.getElementById("deviceID");
localStorage.setItem("deviceID", inputDeviceID.value);
}
I get the device id with a javascript function and push it with ajax into my php script to load the corresponsing data:
function localstoragecheck(){
if (localStorage.getItem("deviceID") === null) {
//alert('no');
}
else {
//alert('yes');
var deviceIDcookie = localStorage.getItem("deviceID");
$.ajax({
url: '/',
data: {'deviceID': deviceIDcookie},
dataType: 'jsonp',
complete : function(){
// alert(this.url)
$.getJSON("/sigfoxdata/" + deviceIDcookie + ".json", function(json) {
console.log(json); // this will show the info it in firebug console
});
}
});
}
}
PHP code for searching the json file and decode it:
$FOLDER = '../sigfoxdata/';
$dir = scandir($FOLDER);
$file = $_GET['deviceID'].'.json' ?: 'DEMO.json';
$fileUrl = $FOLDER.$file;
$file = fopen($fileUrl, "rip");
$lines = fread($file, filesize($fileUrl));
$data = json_decode($lines)->{'data'};
But this is not working, how can I get data from the ajax request in the PHP script?

Related

Saving a JS Variable to Local Storage Passed from PHP

When a build name is clicked the inner html is passed into a JavaScript variable loadDump then passed over to PHP.
$.ajax({
url:"http://custom-assembly.tcad.co.uk/wp-content/themes/custom-assembly/grp-enclosure/load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function(res){
var key_map_obj = '<?php echo $key_map_loaded; ?>';
console.log(key_map_obj);
var key_map_obj_string = key_map_obj;
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
}
})
Once this happens the php in load.php executes. The loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=json_decode($DBP_cols->key_map, true);
}
?>
How can i get $key_map_loaded to pass to the JavaScript and save in the local storage using Ajax.
In you php file try to return the result :
e loadDump variable is used in a sql query to find the matching field.
$loadDump = wp_unslash( $_POST['loadDump'] );
$table_name= $wpdb->prefix. 'product_configurator';
$DBP_results= $wpdb->get_results("SELECT * FROM $table_name WHERE keymap_key = $loadDump");
$DBP_current_user = get_current_user_id();
foreach($DBP_results as $DBP_cols){
$user_id= $DBP_cols->user_id;
$enclosure_type= $DBP_cols->enclosure_type;
$keymap_key= json_decode($DBP_cols->keymap_key, true);
$key_map_loaded=$DBP_cols->key_map;
}
echo $key_map_loaded;
?>
Then in the JavaScript receive it for the ajax request:
$.ajax({
url:"load.php",
method: "post",
data: { loadDump: JSON.stringify( loadDump )},
success: function (data) {
var key_map_obj = data;
console.log(key_map_obj);
var key_map_obj_string = (key_map_obj);
localStorage.setItem("key_map_obj_string", key_map_obj_string);
console.log(localStorage);
},
})

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

Sending a JavaScript array to PHP via POST

I am trying to send a JavaScript array to a PHP file via POST.
JS:
var songlist = ['song1', 'song2', 'song3'];
var sendData = function(){
var data = songList.join(',')
$.post('test.php', {data: data}).always(function() {
window.location = 'test.php';
});
}
sendData();
test.php:
<?php
$songData = $_POST['data'];
$songData = explode(',', $songData);
print_r(array_values($songData));
?>
when sendData(); directs me to test.php I get:
Notice: Undefined index: data
Why doesn't the data variable have any value when I try to print or use it?
That's not how POST request works. Read more about Ajax, but for now, that's how you should do it.
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
$songData = $_POST['data'];
print_r($songData);
?>
1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid.
2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. Thats why its showing "Notice: Undefined index: data"
3) Try to understand how ajax works. Follow it -
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
if(isset($_POST)){
if(isset($_POST['data'])){
$songData = $_POST['data'];
print_r($songData);
}}
?>

Pass data from js to php and download created csv file

I must pass array from JS to PHP using $.post(), create file using array and download it.
Using this pass array:
$('#csv').click(function () {
$.post(
window.location + "crawler/save_to_file",
{
dane: wynik //array
});
});
Now in PHP using this:
$tablica=$_POST['dane'];
$filename = "export-to-csv.csv";
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Expires: 0");
$fh = fopen( 'php://output', 'w' );
$heading = false;
if(!empty($tablica))
foreach($tablica as $row) {
if(!$heading) {
fputcsv($fh, array_keys($row));
$heading = true;
}
fputcsv($fh, array_values($row));
}
fclose($fh);
But when click on button to create and download file, nothing happens.
Thanks
CODE UPDATE
JS file:
$.ajax({
url: window.location + "crawler/",
type: "POST",
dataType: "json",
data: {
wartosc: zmienna
},
success: function (odp) {
wynik = odp; //array
tab = JSON.stringify(odp);
$.post(window.location + "crawler/return_data",
{
data: tab
},
function (data) {
$('#wynik').html(data);
$('.pobierz').show();
}
)
}
})
$('.button').click(function() {
var $form = $('<form action="' + window.location + 'crawler/save_to_csv" method="post"></form>');
$.each(wynik, function() {
$('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
});
$form.appendTo('body').submit();
});
And var_dump array in PHP file:
function save_to_csv()
{
$tablica=$_GET['dane'];
var_dump($tablica);
}
return: "Undefined index: dane"
EDIT
$tablica must be $_POST not $_GET
This can be done with AJAX but you need to use the File api.
So you do something like this:
$.post("csv.php", {
dane: wynik //array
}, function(response){
var blob = new Blob([response], { type:'text/csv' });
alert(URL.createObjectURL(blob));
});
The url you get from the alert, contains your csv file.
And of course if you want to go directly to the file you replace the alert with:
window.location.href=URL.createObjectURL(blob);
UPDATE
If you want to use a custom filename, there is a way to mask the url generated by URL.createObjectURL(), by using an a element.
We than can use the new HTML5 attribute download which allows us to mask the url.
Here is the updated code:
$.post("csv.php", {
dane: wynik //array
}, function(response){
var blob = new Blob([response], { type:'text/csv' }),
a = document.createElement('a'),
url = URL.createObjectURL(blob);
// Put the link somewhere in the body
document.body.appendChild(a);
a.innerHTML = 'download me';
a.href = url;
// Set our custom filename
a.download = 'myfilename.csv';
// Automatically click the link
a.click();
});
Are you forced to use AJAX to send that array to your PHP code? If yes, it is not really possible.
If not, instead of your AJAX call, you could build a hidden form with hidden inputs containing your array items and submit it via JavaScript.
UPDATE
Short example for form built with JS:
$('#csv').click(function() {
var $form = $('<form action="' + window.location + 'crawler/save_to_file" method="post"></form>');
$.each(wynik, function() {
$('<input type="hidden" name="dane[]">').attr('value', this).appendTo($form);
});
$form.appendTo('body').submit();
});

Codeigniter: Uploading image through Ajax and storing in db

I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.

Categories

Resources