15

I have an HTML page with one button, and I need to execute a python script when we click on the button and return to the same HTML page with the result.

So I need do some validation on return value and perform some action.

Here is my code:

HTML:

<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue"></button>

JS:

function validate(){
    if (returnvalue=="test") alert(test)
    else alert ("unsuccessful")
}

What my python code is doing is some validation on the name entered in the text box and gives the return status.

But I need the result back on the same page, so I can do the form submission later with all the details. Any help will be appreciated

Community
  • 1
  • 1
user2058205
  • 997
  • 2
  • 9
  • 17
  • Python runs at server side, so the closest you can get is to AJAX send the value to your server and return the validated result. – Passerby Mar 01 '13 at 05:31
  • 1
    related: [How to connect Javascript to Python sharing data with JSON format in both ways?](http://stackoverflow.com/questions/11747527/how-to-connect-javascript-to-python-sharing-data-with-json-format-in-both-ways) – jfs Mar 01 '13 at 06:23

2 Answers2

15

You can use Ajax, which is easier with jQuery

$.ajax({
   url: "/path/to/your/script",
   success: function(response) {
     // here you do whatever you want with the response variable
   }
});

and you should read the jQuery.ajax page since it has too many options.

martriay
  • 5,632
  • 3
  • 29
  • 39
12

Make a page(or a service) in python, which can accept post or get request and process the info and return back a response. It is better if the response is in json format. Then you can use this code to make a call on the button click.

<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){

 $.ajax({
      type:'get',
      url:<YOUR SERVERSIDE PAGE URL>,
      cache:false,
      data:<if any arguments>,
      async:asynchronous,
      dataType:json, //if you want json
      success: function(data) {
        <put your custom validation here using the response from data structure >
      },
      error: function(request, status, error) {
        <put your custom code here to handle the call failure>
      }
   });
});
</script>

I hope this helps

Xetnus
  • 353
  • 2
  • 4
  • 13
Hari
  • 310
  • 3
  • 14
  • @Hari May I ask what the $('#id') is doing? is the '#id' used here as a placeholder for us to replace with something like 'home' (in the case of OP's question)? If so, I'm still not sure what $ is doing – hello_there_andy Nov 23 '16 at 13:48
  • @hello_there_andy, the "id" is supposed to be replaced with the id of your html element. '#' denotes that it is an id jquery should be looking for. $ is the jquery object and it invokes the jquery library. – Hari Nov 30 '16 at 22:19