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.
Related
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().
I currently have a javascript variable called myVariableToSend that contains a single string and I need to send to my views where I can make raw SQL queries to gather corresponding data from the database and bring it back to my javascript. Here is what I have:
Javascript:
function scriptFunction(myVariableToSend){
$.getJSON("http://127.0.0.1:8000/getData/", myVariableToSend, function(serverdata){
window.alert(serverdata);
});
Views.py:
def getData(request):
some_data = request.GET(myVariableToSend)
cursor = connection.cursor()
cursor.execute("SELECT Car_ID FROM cars WHERE Carname = %s ", [some_data])
row = cursor.fetchall()
return JsonResponse(row, safe = False)
Urls.py:
url(r'^admin/', include(admin.site.urls)),
url(r'^$', startpage),
url(r'^getData/$', getData ),
I don't think my server side script(views.py) is working because when I run my server, I get a http500 error. Any help would be appreciated. Thank you.
UPDATE:
I have found that when I comment out my entire Views.py and only put
def getData(request):
return JsonResponse({"hello":"World"}, safe = False)
I get no problems and the AJAX request works. But when I have my original getData, it doesn't work. When I add this line in my views.py:
some_data = request.GET(myVariableToSend)
, I get an error and the data isn't displayed
If u want to send ur variables to function in view, u can capture it with url, like this:
$.getJSON('http://127.0.0.1:8000/getData/' + myVariableToSend +'/', function (serverdata) { //do ur work}
Then in urls.py you have:
url(r'getData/(?P<my_var>\w+)/$', views.get_data, name='get_data')
Then views.py:
def get_data(request, my_var):
#do ur work here
Answering the original question:
Your server is failing probably because bad syntax in views.py
some_data = request.GET(myVariableToSend)
myVariableToSend is undefined here. So you should get it like this:
some_data = request.GET['myVariableToSend']
Besides the original question:
You'll get a lot of headaches if you try to set up your django app like this.You can query your database way easier if you use django's ORM. Read about it here.
Also, if you want to send the data in your models to your javascript code, you can save yourself lots of time by using a framework like Django REST Framework.
Probably a stupid issue, but I am stuck.
I have a node.js server that sends data to a client, like this:
var message_to_client = result;
socket.send(JSON.stringify(message_to_client));
Client succesfully receives the data; if I log it on console, it reads like this:
[{"_id":"55e60d3de4b06ef3ed5f189e","par1":54.2441033, "par2":-10.177503399999999}]
I want to show the par1 value on screen, however I don't seem to be able to 'extract' it from the JSON response.
I tried with the parseJSON function from jQuery and with https://stackoverflow.com/a/22628619/3849735, neither worked.
Anyone can help? Thanks.
Send the response in json format instead in string, like
var message_to_client = result;
socket.send(message_to_client);
client side
data[0].par1
will return the values
I get the feeling I really should be learning WCF for this (feel free to comment if you agree), but, I want to query a website and get a result back, in either XML or JSON format.
In this case, I'm choosing JSON.
I have a controller in a web site (www.site1.com) , which looks like
public JsonResult Save(bool willSave)
{
//logic with the parameters to go here
return Json(new { code = 200, description = "OK" }, JsonRequestBehavior.AllowGet);
}
Now, I'd like to get this information from another website, so in www.site2.com I have nothing... I have no idea what code I can write, simply because all of the examples I've seen where you query json uses javascript/Ajax.
I don't want to use JavaScript or Ajax (I know how to do that), for this project I'm trying to do everything I can server side.
I'd like to be able to do the following
public ActionResult Do()
{
var json = someHowQuerySite1.com?withQueryString=true;//THIS IS THE ISSUE
var model = CreateModel(json);
return View(model);
}
As you can hopefully see,
var json = someHowQuerySite1.com?withQueryString=true;//THIS IS THE ISSUE
I don't know what syntax to write here.
The simplest way, replace
var json = someHowQuerySite1.com?withQueryString=true;
with
using (var client = new HttpClient())
{
var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx?withQueryString=true");
var json = myJsonUtililty.toJson(responseString);
}
HTTP request with post
You want to use a HttpWebRequest to request www.site1.com/Save?save=true. Something like
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://[urlhere]");
HttpWebResponse response = request.GetResponse();
using(Stream responsestream = response.GetResponseStream())
{
//Get your JSON from the stream here
}
Use something like this
var response = client.PostAsJsonAsync("UserApi/ValidateUserLogin", new UsersBLL { Username = userName, UserPassword = password }).Result;
and python/cherrypy server
#cherrypy.tools.json_out()
#cherrypy.tools.json_in()
def get_data(self):
cherrypy.response.headers['Content-Type'] = 'application/json'
datas = {"ABCDEF"}
return datas
but I get a Internal Server Error (500), where is my mistake?
I get work to post data to server, but with getting data is my problem..
One problem is in your fifth line of your second code block. Change
datas = {"ABCDEF"}
to something like
datas = { "somedata" : "ABCDEF"}
And if this is all of your cherrypy server code, you're not exposing your route. Then you have to add the
#cherrypy.expose
annotation. You can consult the docs for this as well.
Your datas variable is a Python set, and those are not directly serialisable to JSON. Perhaps you meant to create a dictionary or list?