Problems calling PHP function from Javascript - 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/

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?

Running CGI Python Javascript to retrieve JSON object

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.

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!

Ajax in Codeigniter doesn't work for a specific controller in remote host

My web application does Ajax request to a Codeigniter-php code in a remote server. It works in localhost but not with a specific controller in remote host. It is strange because works in localhost for both controllers.
The request:
$.ajax({
async:true,
type: "POST",
dataType: "json",
url:"/CI/site/index.php/contact/submitContact",
data: "", //data example
success:arrived,
error:problems });
function arrived(data){
var dataJson = eval(data);
}
function problems(){
$("#result").text('Problems.');
}
I check the arrived with log_message. With the next function works fine:
function submitContact(){
log_message('error', 'submitContact. ');
//If data are received
if($_POST){
log_message('error', 'data. [application/controllers/contact.php]');
}
}
However, If I change the request to url:"/CI/site/index.php/control/controlHome", there isn't any log message and the output is the next:
POST http://www.page.com/CI/site/index.php/control/controlHome 500 (Internal Server Error)
The function /application/controllers/control.php is the next:
function controlHome(){
log_message('error', 'controlHome. [application/controllers/control.php]');
//If data are received
if($_POST){
log_message('error', 'data. [application/controllers/control.php]');
}
}
Also I've tried with complete url in the ajax code but the result is the same. Any setting is required?
Check this AJAX csrf protection with codeigniter 2. This solve my same problem
http://aymsystems.com/ajax-csrf-protection-codeigniter-20
UPDATE:
I checked your control.php file on my test server.
if($_POST) { /* i only commented gangway library functions */
} else { /* only replace the load->view with an print_r $data; and its work */ }
And put to comment the gangway library on construct. And control/controlHome works normaly without any error. Check your gangway library THAT's cause error 500.

Understanding how to use CGI and POST

I'm trying to understand how I can use Python and javascript so that I can use POST/GET commands. I have a button that sends a request to server-side python, and should return a value. I understand how to print out a response, but I want to pass a value to a javascript variable instead of just print thing the response.
For example, my javascript sends a string to the python file using the jquery POST function:
<script>
function send(){
$.ajax({
type: "POST",
url: "pythondb.py",
data:{username: 'william'},
async: false,
success: function(){
alert('response received')
},
dataType:'json'
});
}
</script>
Then using the python cgi module I can print out the value of username:
#!/usr/bin/env python
import cgi
print "Content-Type: text/html"
print
form = cgi.FieldStorage()
print form.getvalue("username")
however I am not receiving the data in the same way that the php echo function works. Is there an equivalent to 'echo' for the python cgi module?
I have read this question which explains the different python frameworks that can be used to communicate between browser and server; for the moment I was hoping to keep things as simple as possible and to use the cgi module, but I don't know if that is the best option.
Your success: function can take a parameter, to which jQuery will pass the contents of the response from the AJAX request. Try this and see what happens:
<script>
function send(){
$.ajax({
type: "POST",
url: "pythondb.py",
data:{username: 'william'},
async: false,
success: function(body){
alert('response received: ' + body);
},
dataType:'json'
});
}
</script>
P.S. Why are you using async: false? That kind of defeats most of the point of AJAX.
Your json is not in proper json format.
According to http://api.jquery.com/jquery.parsejson/,
username needs to be in quotes
you can only use double quotes
It would look like this:
{"username": "william"}
Also, your alert should have a semi colon on the end. I can't guarantee this answer will fix your problem, but it may be that your data isn't getting passed to cgi at all.

Categories

Resources