0

Hello I have a python script that I'm trying to run from PHP from the client side using an AJAX call like this :

$.ajax({
async: false,
cache:false, 
url:"callpython.php",
type: "POST",
data: "data1=" + path + "&data2=" + clr[k0], 
success: function (response) {
console.log(response);
}});

the code inside callpython.php is:

<?php
exec("python myscript.py",$return);
echo json_encode($return);
?>

and the code inside myscript.py is:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import string
import cgi, cgitb
from lxml import etree
from PIL import Image

pet="images/rock1.png"
petColor="59A678"
.//The rest of the code that populates the variables printed down below
.
.
.
print "Content-type: text/html"
print 
print eyeSize
print displacementX
print displacementY
print distance
print textX
print textY 
print sizeText
print colorText

As Ajax result I get : Array

When I run the php code from console : php callpython.php it executes the python script and it gives me : ["Content-type: text\/html","","30","37","47","20","27","40","20","#91806F"] but when calling that same php file using ajax Firebug shows me : [] as result.

So please how can I get the same result in that Ajax call as the console results?

Thanks.

2 Answers 2

2

As a first step, I would try outputting json from python. What you are getting from python currently is a bunch of lines (a single string), not a valid json encodable list. Also, you wouldn't need the Content-Type in the data as that is a header for use in HTTP. Instead, try this:

PYTHON

import json
...
data_out = [eyeSize, displacementX, ...]
print json.dumps(data_out)

PHP

exec("python myscript.py",$return);
echo $return;
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for the reply, I did as you suggest me, now when running the php script from console I get :["[\"30\", \"37\", \"47\", \"20\", \"27\", \"40\", \"20\", \"#91806F\"]"] and now the AJAX call gives me : Array instead of [] so the issue is still unsolved.
Hi I fix it, it was an error in my python code and I used passthru() function instead of exec() header("Content-type: text/html"); echo passthru("python eyes/cgi-bin/eyes.py");
0

try to set header as below,

header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);

1 Comment

Hi, sorry but I get the same result as before : []

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.