gzinflate string compressed via JS - javascript

I'm trying to compress a massive JS object on the client side via Pako and than get it back on the PHP-script.
JS code
const save_str = JSON.stringify(massive_object);
const gz_str = pako.gzip(save_str, { to: 'string' });
$.post('/',
{data:window.btoa(unescape(encodeURIComponent(gz_str)))},
(data)=>{ console.log(data); },
'json');
PHP code
$res = gzinflate(base64_decode($_POST['data']));
Should be quite straight-forward thing but I keep getting gzinflate(): data error.
Already spent a few hours dancing around, still no result. Begging for help!

You want gzdecode(), not gzinflate().

Related

Why string get from buffer does not equal to JavaScript String

I am working on a project in which I am using node js and python together. My node js code makes a child process of python code. And I am sending some data from node js to python and also receiving some data back from python to node.
I call my python file like this.
const py = spawn('python', ['file.py', 'some_data']);
and for sending data back from python to node I am using print in python like this.
print("mydata")
and for receiving in nodejs I am using this code.
py.stdout.on('data', async (data) => {
//This data is python string as we can see above
var data_from_python = data.toString();
});
now the problem I am facing is string which come from python does not equal to node js string I have tried this.
data_from_python === "mydata" // false
and also this
data_from_python == "mydata" // false
both returns false.
But when I console the type of both using typeof operator it says string for both.
I want to know what is reason behind and what is the solution if we want to compare them or is there a better way to get data back from python to node. I know this "mydata" string is coming from buffer, python is putting it into the buffer and node is reading it from the buffer, and I think they both are different because one is python string and other is nodejs string, maybe it is because of under the hood both deal or make strings differently.
But what is the exact story behind if anyone one know please share your knowledge.
This is because print in python adds a new line after the data, So instead of getting mydata you will receive mydata\r\n. So you should check for the same in your condition, see below:
const { spawn } = require('child_process')
const py = spawn('python', ['py.py', 'some_data']);
py.stdout.on('data', async (data) => {
console.log(data);
var data_from_python = data.toString();
console.log(data_from_python == "mydata\r\n"); // outputs true
});

Troubleshooting HTTP request and JSON message on Django

Okay, so I have been going at this for a while and it doesn't seem like I am getting anywhere. I am running a Django app with Nginx and uwsgi. I have an http.post and I am trying to even read the items which I keep getting errors for.
This is what my JS code looks like :
$scope.receipt_pay_update = function(items)
{
response = confirm("Do you want to continue with the changes?");
if(!response){
return;
}
var data = {
'items': items,
'time_now': moment().format("YYYY-MM-DD")
};
items.showmessage = true;
console.log(data)
$http.post("/foodhub/dashboard/receipt_pay_modal_update", data,{
data: JSON
}).
success(function(data,status,headers,config){
$scope.alertclass = 'alert-success';
$scope.save_message_farmer = "Succcessfully update payment"
console.log("SAVED!")
}).
error(function(data,status,headers,config){
$scope.alertclass = 'alert-danger';
$scope.save_message_farmer= "Failed to update inventory, please try again"
})
}
This is what my views.py looks like:
#login_required
def receipt_pay_modal_update(request):
import sys
reload(sys)
sys.setdefaultencoding('utf8')
data = json.loads(request.body)['items']
print data
rec = ReceiverActions.objets.get(identifier = data[0]['identifier'])
rec['paid_check'] = data[0]['paid_status']
rec['date_paid'] = data[0]['paid_date']
rec.save()
return HttpResponse(status=status.HTTP_200_OK)
I got an error of unable to decode JSON. So I tried data = request.body[0] which also didn't work.
Is there any other way I could be testing small changes on my server without having to do the Git push, Git Pull, Python -m compileall ., etc? The reason I ask is because I was taught to do it this way by practice and I feel there is a better way.
Where can I check my print data?
Any help would be highly appreciated.
Turns out the data I was getting was not JSON appropriate. I went back and changed the request to send data as a json and it worked perfectly.

using ajax to send javascript data to php

so i've been looking at how to record and send client-side data to a php server.
i'm not sure of the correct terminologies, but i think that using an ajax call to send a post to the php server is the most elegant way to solve this problem.
so i decided to implement this data exchange:
$("#"+activityInfo.ID).click(function(){
window.open(activityInfo.URL+"userId="+$("#userid").val()+"&activityId="+activityID+"&classId="+classID);
classid = classID;
activityid = activityID;
$("body").append("class: " + classid);
$("body").append("id: " + activityid);
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { 'cid':classid , 'aid':activityid } );}); //i think this is the important line that sends the data
and the corresponding php file (updateProgress.php)
$class_id = $_POST['cid']; //receives the data
$activity_id = $_POST['aid'];
i'm not sure why this is the case, but class_id and activity_id variables always return an empty value.
i understand somewhat that the client-browser is on a page that is preloaded by information from a php server. but there were posts that said this is a possible way to communicate back to the php server with information from the client. i'm not really sure what is going on b/c at this point i don't really know what questions to ask.
one of the example explanations that i had been following:
Ajax passing data to php script
thanks for the help.
i've also played around with start_session() and storing/loading session variables as a way to transfer data information. this works but only for php <-> php communication. it does not for saving javascript variables, so i couldn't really use $_SESSION = ..... in my javascript code.
you need to get the cid and aid outside of the single-qouts while using $.post! try this:
$.post('http://chemcollective.org/chemvlab/php/updateProgress.php', { cid:classid , aid:activityid } );

Form data not passing to PHP file

The Program I'm writing and the functionality I'm trying to achieve
Okay. So what I'm writing at the moment is a very simple forum, in Javascript using AJAX. Part of my task is to add a new post, using an API that my lecturer wrote for us in PHP. Just to note, the API and the SQL database are completely local.
The function I am using to add this post is:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
'method':'post',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).send(Object.toQueryString({
// Had to convert it to a query string because it wouldn't work as a normal object.
// These are the required values to send, to store a "post" in the database.
'name':'This is a name',
'comment':'This is a comment!'
}));
}
I am aware this will add the same data every single time. I'm just trying to get the damn thing working!
The problem
What is happening is, when this function is called, I am getting an SQL syntax error. I was confused, because that would imply that my lecturer's code is wrong. After speaking with my lecturer, he explained that this happens when the post data isn't sent correctly to the PHP code. So I went about using Google Chrome's developer tools to see what was going on, and this is what I discovered:
Now to me, this means that the data is successfully being loaded into the request, and is being passed to the PHP files fine. Obviously I'm wrong. I've been racking my brains trying to make this work.
I know that the API works fine, because everyone else in my class isn't having any problem with it, and the code I am using is practically a rip off of the code in the notes, so I'm about 90% sure that's correct to.
One thing to note is that the code in the onSuccess key runs, so I know it's not a problem on the AJAX side.
Another thing is that this code worked in University on those computers, and it's since I've got it home that it's decided not to work.
Stack Trace
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000]: General error: 1 near ")": syntax error' in G:\Ajax
Coursework\guestbook\php\database.php:134Stack trace:#0 G:\Ajax
Coursework\guestbook\php\database.php(134): PDO->prepare('INSERT INTO
pos...')#1 G:\Ajax Coursework\guestbook\php\class.GuestBook.php(44):
DatabaseHandler->insert(Array)#2 G:\Ajax
Coursework\guestbook\control.php(8): GuestBook->insert(Array)#3
G:\Ajax Coursework\guestbook\control.php(56): insertPost()#4 {main}
thrown in G:\Ajax Coursework\guestbook\php\database.php on line 134
Object.toQueryString is used in convert an object to a query string. So if the server is requiring both $_POST['name'] and $_POST['comment'] to be set, it wont be.
Frankly because you are posting it, I dont think $_GET['name'] or $_GET['comment'] would be set either.
Request.send expects an opject. You are sending it a string. So it should be
Request.send({prop: 'value'}), not Request.send(value).
Do yourself a favor and make a PHP with the following php code, and see what it returns. It may clear this up for you right away. I have a feeling nothing is being sent except for $_GET['action']
<?php
echo '<pre>';
print_r($_GET);
print_r($_POST);
echo '</pre>';
?>
Just in-case anyone stumbles upon this thread looking for an answer:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).post('name=This is a name&comment=This is a comment!');
}
Here I'm using the .post method to POST data.

How to get JSON from PHP to JS?

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.
Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});
Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH

Categories