Running CGI Python Javascript to retrieve JSON object - javascript

I want to use javascript to retrieve a json object from a python script
Ive tried using various methods of ajax and post but cant get anything working.
For now I have tried to set it up like this
My Javascript portion:
I have tried
$.post('./cgi-bin/serverscript.py', { type: 'add'}, function(data) {
console.log('POSTed: ' + data);
});
and
$.ajax({
type:"post",
url:"./cgi-bin/serverscript.py",
data: {type: "add"},
success: function(o){ console.log(o); alert(o);}
});
My Python
import json import cgi import cgitb cgitb.enable() data = cgi.FieldStorage()
req = data.getfirst("type") print "Content-type: application/json"
print print (json.JSONEncoder().encode({"status":"ok"}))
I am getting a 500 (internal server error)

Have you tried doing just
print (json.JSONEncoder().encode({"status":"ok"}))
instead of printing the content-type and a blank line?

Have you checked your host's server logs to see if it's giving you any output?
Before asking here, a good idea would be to ssh to your host, if you can, and running the program directly, which will most likely print the error in the terminal.
This is far too general at the moment, there are so many reasons why a CGI request can fail ( misconfigured environment, libraries not installed, permissions errors )
Go back and read your servers logs and see if that shines any more light on the issue.

Related

Python code not being executed with Ajax get request

I have this python code:
from twilio.rest import Client
account_sid = "myID"
auth_token = "myAuth"
client = Client(account_sid, auth_token)
client.api.account.messages.create(
to="+num1",
from_="num2",
body="Hello there!")
and when I execute it on the command line python file.py everything works fine,(aka a text is sent to my phone) but I want to execute this code from a javascript file and I am doing this:
$.ajax({
type: "GET",
url: "file.py",
}).done(function( o ) {
console.error("WOW")
});
but the python is not being executed although I do see the console error. I'm not too sure whats going on, I'm wondering if this needs to be changed to a POST request, but that simply gives me a 404 not found error.
I don't think we can give a python filename as url value. AJAX will send a request to the server and in order to handle that request we will need a server side scripting language.
Below link explains how to handle AJAX request in Django.
How do I integrate Ajax with Django applications?

Passing a string from Python to Javascript

I'm trying to pass a string from Python to Javascript via ajax POST request but i'm finding serious difficulties.
I've tried both with and without using JSON.
Here's the code
JAVASCRIPT
$.ajax({
url: url, #url of the python server and file
type: "POST",
data: {'data1': "hey"},
success: function (response) {
console.log(" response ----> "+JSON.parse(response));
console.log(" response no JSON ---> " +response);
},
error: function (xhr, errmsg, err) {
console.log("errmsg");
}
});
Python
import json
print "Access-Control-Allow-Origin: *";
if form.getvalue("data1") == "hey":
out = {'key': 'value', 'key2': 4}
print json.dumps(out)
Result is a empty JSON. when i do something like JSON.parse in javascript I get a unexpected end of input error, and when i try to get the length of the response data the size I get is 0.
I suppose that there should be some problems with the client server communication (I use a CGIHTTPServer) or maybe something wrong with the datatype that python or javascript expects.
I also tried without JSON, with something like
Python
print "heyyyyy"
Javascript
alert(response) //case of success
but I also got an empty string.
Could you please give me some advices for handling this problem ?
Thanks a lot!
You may want to compare the two snippets of code CGIHTTPRequestHandler run php or python script in python and http://uthcode.blogspot.com/2009/03/simple-cgihttpserver-and-client-in.html.
There isn't enough code to tell where your request handling code is but if it's in a class inheriting from CGIHTTPRequestHandler then you need to use self.wfile.write(json.dumps(out)), etc.
I managed to solve the problem using the method HTTPResponse from the Django Framework.
Now it's something very similar to this
PYTHON (answering the client with a JSON)
from django.http import HttpResponse
...
data = {}
data['key1'] = 'value1'
data['key2'] = 'value2'
.....
response = HttpResponse(json.dumps(data), content_type = "application/json")
print response;
JAVASCRIPT (Retireving and reading JSON)
success(response)
alert(JSON.stringify(response));
Or if I just want to send a String or an integer without JSON
PYTHON (no JSON)
response = HttpResponse("ayyyyy", content_type="text/plain")
print response
JAVASCRIPT (Retrieving String or value)
success: function (response) {
alert(response);
This works very good, and it's very readable and simple in my opinion!
Instead of print json.dumps(out) you should use return json.dumps(out)
The print will only display it in python's console, just as console in javascript.

Problems calling PHP function from Javascript

[Solved] check out the link by Jonathan M
Reason: SimpleHTTPServer doesn't handle POST
Other tips: I ran into another issue where the server was returning the entire .php file, instead of the value. This is because python server doesn't handle php by default. An easy get-around was to spin up a php server via php -S youraddress:port
I'm having problems calling php functions from javascript. I have tried some of the suggestions on stackoverflow without any success. I'm not sure what I'm missing here...
I'm writing to submit a simple POST request to my php file, but I get this error in my browser console:
POST http://localhost:8000/myphp.php 501 (Unsupported method ('POST'))
I'm writing a single page web app that is currently running on my local machine with a simple server running at /projecthome/
python -m SimpleHTTPServer
My files are laid out like this:
/projecthome/index.html
/projecthome/myphp.php
/projecthome/js/myjs.js
index.html:
...
<script src="js/myjs.js" type="text/javascript"></script>
<script>
$(function() {
run();
});
</script>
...
myjs.js:
function schemaCreationTool() {
var id='someID';
$.ajax({
url: 'myphp.php',
type: 'POST',
data: {id:id},
success: function(data) {
console.log(data);
}
});
}
myphp.php:
<?php
if (isset($_POST['id'])) {
select($_POST['id']);
}
function select($x) {
echo "The select function is called.";
}
}
I followed solutions from these posts:
calling a php function in javascript
Call php function from javascript and send parameter
Python's SimpleHTTPServer doesn't natively support POSTs. You can extended it to do so with this little handler:
http://georgik.sinusgear.com/2011/01/07/how-to-dump-post-request-with-python/

Calling a Python script from Javascript, both local files

I'm trying to run a python script from a local javascript file (part of a locally running HTML/javascript program).
I've been googling this for hours and found a lot of solutions, none of which actually work for me.
Here is the javascript:
$.ajax({
type: "POST",
url: "test.py",
data: { param: " "}
}).done(function( o ) {
alert("OK");
});
The test.py file is in the same folder as the script/html file.
here is the script:
#!/usr/bin/python
import os
filepath = os.getcwd()
def MakeFile(file_name):
temp_path = filepath + file_name
with open(file_name, 'w') as f:
f.write('''\
def print_success():
print "sucesss"
''')
print 'Execution completed.'
MakeFile("bla.txt");
It works fine when run normally.
On my Firefox console I get a "not well formed" error and the script doesn't create a file. However, I can see that Firefox does fetch the script, as I can view it in my browser by clicking the file name.
In order for the python script to execute it has to be deployed by a web server that supports it via CGI or WSGI, etc.
Check out the docs here: webservers
There are three problems with your code.
First, when you call $.ajax(), it tries to parse the response as either JSON or HTML. To prevent it, use dataType: "text".
$.ajax({
type: "POST",
url: "111212.py",
data: { param: " "},
dataType: "text"
}).done(function( o ) {
alert("OK");
});
Second, fetching a local file from javascript may violate the Same Origin Policy, depending on the browser. See: Origin null is not allowed by Access-Control-Allow-Origin
An most important, fetching does not execute a file, it just reads it and returns as a string.
So apparently, as has been pointed out, this can't be done, not like this. So I'm going to start a simple CGI python sever to server the HTML file, and execute the script. I've tested it and it works great!

JQuery Ajax Post results in 500 Internal Server Error

I am trying to perform this AJAX post but for some reason I am getting a server 500 error. I can see it hit break points in the controller. So the problem seems to be on the callback. Anyone?
$.ajax({
type: "POST",
url: "InlineNotes/Note.ashx?id=" + noteid,
data: "{}",
dataType: "json",
success: function(data) {
alert(data[1]);
},
error: function(data){
alert("fail");
}
});
This is the string that should be returned:
{status:'200', text: 'Something'}
I suspect that the server method is throwing an exception after it passes your breakpoint. Use Firefox/Firebug or the IE8 developer tools to look at the actual response you are getting from the server. If there has been an exception you'll get the YSOD html, which should help you figure out where to look.
One more thing -- your data property should be {} not "{}", the former is an empty object while the latter is a string that is invalid as a query parameter. Better yet, just leave it out if you aren't passing any data.
in case if someone using the codeigniter framework, the problem may be caused by the csrf protection config enabled.
This is Ajax Request Simple Code To Fetch Data Through Ajax Request
$.ajax({
type: "POST",
url: "InlineNotes/Note.ashx",
data: '{"id":"' + noteid+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
},
error: function(data){
alert("fail");
}
});
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
type:'POST'
I experienced a similar compound error, which required two solutions. In my case the technology stack was MVC/ ASP.NET / IIS/ JQuery. The server side was failing with a 500 error, and this was occurring before the request was handled by the controller making the debug on the server side difficult.
The following client side debug enabled me to determine the server error
In the $.ajax error call back, display the error detail to the console
error: (error) => {
console.log(JSON.stringify(error));
}
This at least, enabled me to view the initial server error
“The JSON request was too large to be serialized”
This was resolved in the client web.config
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
However, the request still failed. But this time with a different error that I was now able to debug on the server side
“Request Entity too large”
This was resolved by adding the following to the service web.config
<configuration>
…
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferPoolSize="524288">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
The configuration values may require further tuning, but at least it resolved the server errors caused by the ajax post.
You can look up HTTP status codes here (or here), this error is telling you:
"The server encountered an unexpected condition which prevented it from fulfilling the request."
You need to debug your server.
I run into the same thing today. As suggested before get Firebug for Firefox, Enable Console and preview POST response. That helped me to find out how stupid the problem was. My action was expecting value of a type int and I was posting string. (ASP.NET MVC2)
There should be an event logged in the EventVwr (Warning from asp.net), which could provide you more details on where the error could be.
A 500 from ASP.NET probably means an unhandled exception was thrown at some point when serving the request.
I suggest you attach a debugger to the web server process (assuming you have access).
One strange thing: You make a POST request to the server, but you do not pass any data (everything is in the query string). Perhaps it should be a GET request instead?
You should also double check that the URL is correct.
I just face this problem today. with this kind of error, you won't get any responses from server, therefore, it's very hard to locate the problem.
But I can tell you "500 internal server error" is error with server not client, you got an error in server side script. Comment out the code closure by closure and try to run it again, you'll soon find out you miss a character somewhere.
You can also get that error in VB if the function you're calling starts with Public Shared Function rather than Public Function in the webservice. (As might happen if you move or copy the function out of a class). Just another thing to watch for.
Can you post the signature of your method that is supposed to accept this post?
Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:
<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
$.ajax({
type:'POST',
url:url,
data:message,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:successFunc,
error:errorFunc
});
};
Then my errorFunc javascript is like this:
function(request, textStatus, errorThrown) {
$("#install").text("Error doing auto-installer search, proceed with ticket submission\n"
+request.statusText); }
Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery's library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:
<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>
so check all that, and post your controller method signature in case that's part of the issue
I found myself having this error to. I had .htaccess redirect configured in a directory. Well it reroutes ajax calls to ofcourse ($.post(../ajax.php)), so it couldn't find the actual file (resulting in 500 error).
I 'fixed' it by placing the ajax.php in a directory (So .htaccess didn't affect).
I was able to find the solution using the Chrome debugger (I don't have Firebug or other third-party tools installed)
Go to developer tab (CTRL+MAJ+I)
Network > click on the request which failed, in red > Preview
It showed me that I had a problem on the server, when I was returning a value which was self-referencing.
In my case it was simple issue, but hard to find. Page directive had wrong Inherits attributes. It just need to include the top level and it worked.
Wrong code
<%# Page Language="C#" CodeBehind="BusLogic.aspx.cs" Inherits="BusLogic"%>
Correct code
<%# Page Language="C#" CodeBehind="BusLogic.aspx.cs" Inherits="Web.BusLogic" %>
When using the CodeIgniter framework with CSRF protection enabled, load the following script in every page where an ajax POST may happen:
$(function(){
$.ajaxSetup({
data: {
<?php echo $this->config->item('csrf_token_name'); ?>: $.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>')
}
});
});
Requires: jQuery and jQuery.cookie plugin
Sources: https://stackoverflow.com/a/7154317/2539869 and http://jerel.co/blog/2012/03/a-simple-solution-to-codeigniter-csrf-protection-and-ajax
The JSON data you are passing to the server should have same name as you forming in client side.
Ex:
var obj = { Id: $('#CompanyId').val(),
Name: $("#CompanyName").val()
};
$.Ajax(data: obj,
url: "home/InsertCompany".....
If the name is different, ex:
[HttpPost]
public ActionResult InsertCompany(Int32 Id, string WrongName)
{
}
You will get this error.
If you are not passing the data, remove the data attribute from AJAX request.
I had this issue, and found out that the server side C# method should be static.
Client Side:
$.ajax({
type: "POST",
url: "Default.aspx/ListItem_Selected",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: ListItemElectionSuccess,
error: ListItemElectionError
});
function ListItemElectionSuccess(data) {
alert([data.d]);
}
function ListItemElectionError(data) {
}
Server Side:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static String ListItem_Selected()
{
return "server responce";
}
}
As mentioned I think your return string data is very long. so the JSON format has been corrupted.
There's other way for this problem. You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
Use a Try Catch block on your server side and in the catch block pass back the exception error to the client. This should give you a helpful error message.
I also faced the same problem. Here are two ways by which I have solved it-
1. If you're using some framework, make sure you are sending a CSRF token with the ajax call as well
Here is how the syntax will look like for laravel -
<meta name="_token" content="{{ csrf_token() }}">
In your js file make sure to call this before sending the ajax call
$.ajaxSetup({
headers: {
'X_CSRF-TOKEN' : $('meta[name="_token"]').attr('content')
}
});
Another way to solve it would be to change method from post to get
For me, the error was in php file to which i was sending request.
Error was in database connectivity. After fixing the php code, error resolved.
Your code contains dataType: json.
In this case jQuery evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner. Any malformed JSON is rejected and a parse error is thrown. An empty response is also rejected.
The server should return a response of null or {} instead.
I found this occurred in chrome when I did two ajax queries in the jquery 'on load' handler,
i.e. like $(function() { $.ajax() ... $.ajax() ... });
I avoided it using:
setTimeout(function_to_do_2nd_ajax_request, 1);
it's presumably a chrome and/or jquery bug
I had this problem because the page I called ajax post from had EnableViewState="false" and EnableViewStateMac="false" but not the page called.
When I put this on both pages everything started to work. I suspected this when I saw MAC address exception.
Your return string data can be very long.
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
For example:
1 Char = 1 Byte
5 Char = 5 Byte
"Hakki" = 5 Byte
I have had similar issues with AJAX code that sporadically returns the "500 internal server error". I resolved the problem by increasing the "fastCGI" RequestTimeout and ActivityTimeout values.
I'm late on this, but I was having this issue and what I've learned was that it was an error on my PHP code (in my case the syntax of a select to the db). Usually this error 500 is something to do using syntax - in my experience. In other word: "peopleware" issue! :D
As an addition to the "malformed JSON" answer, if the query you are running returns an object or anything that prevents the data to be serialised, you will get this error. You should always be sure you have JSON and only JSON at the end of your action method or whatever it is you are getting the data from.
Usually your property is not completely right or something wrong with your server processing.

Categories

Resources