Execute a python script on button click - javascript

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

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.

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

Related

jQuery Ajax loop on form submit

New to Ajax, however, I can't figure out what is wrong, and I assume its the Javascript. My php page is working just fine, however, with this code my login Html simply refreshes over and over with the end of the url changing to ?username=whatIenter&password=whatIenter
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('#login_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/lib/login.php',
data: $(this).serialize(),
success: function(data)
{
alert("WORKED");
}
});
});
});
</script>
HTML
<form id="login_form" action="" method="POST">
<input type="text" id="user" name="username">
<input type="password" id="pass" name="password">
<button id="loginButton" class="login_submit" type="submit" >Login</button>
</form>
First of all, which jQuery version are you using?
Your code is working fine with jQuery 3.3.1
Always keep in mind this good practices:
Disable the cache on your browser while you develop
Each time you wanna check your site, open the browser console and then press F5
Javascript code always needs to stay at bottom inside body tag (just before </body>)
This also apply in the case you put it on a separated file (recommended)
Set the action parameter on your form, this can prevent unexpected errors
Even if you are gonna call the same file or url
Try:
var header = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
};
var request = $.ajax({
url: '/lib/login.php'
,data: $(this).serialize(),
,headers: header
});
request.done(function(response) {
alert("WORKED "+response);
});
The thing is, some/most API's will require you to explicitly specify the content type, before they return the "standard" HTTP response that your Javascript will read.
Resources:
https://web.archive.org/web/20210816145541/https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

how to execute first php function than javascript function onclicking/submiting a submit button

i have this input field:
<input type="submit" name="rregjistro" value="Rregjistro Tani Te Dhenat" onclick="openmodal()" >
I want first to execute POST script in PHP and than to open a modal popup using a javascript function.
Can you please help me!
Thanks in advance!
It is not possible to click using PHP because form submission is the action on the client's side, i.e in your browser. Events in the browser like this can be executed by javascript or other client language.
<form ... >
<input type="submit" name="rregjistro" value="Rregjistro" />
<!-- remove onclick attribute for now -->
</form>
<div id="myResult"></div>
<script>
$(function(){
$("input[name=rregjistro]").click(function(){
// url needs to belong to your domain
$.ajax({url: "/your_url_path", success: function(result){
$("#myResult").html(result);
open();
}});
});
});
</script>
You would still need to start with a javascript function first.
In jquery that would be something like that:
function open() {
$.post('http://url', $('#form').serialize(), function() {
alert('popup goes here');
})
)

Post Method to URL from a onclick function

I need help on something that sounds easy but is difficult for me.
So when someone clicks on this div:
<div onclick="<go to url sending data using the post method>">Click Me</div>
I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.
If you need to use div you can do it like this but I suggest that you use button or input of type submit.
<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>
Also you may use jQuery or some other JS library.
NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.
Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.
//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="someInput">
<div onclick="sendData()">Click Me</div>
<script>
function sendData(){
//get the input value
$someInput = $('#someInput').val();
$.ajax({
//the url to send the data to
url: "ajax/url.ajax.php",
//the data to send to
data: {someInput : $someInput},
//type. for eg: GET, POST
type: "POST",
//datatype expected to get in reply form server
dataType: "json",
//on success
success: function(data){
//do something after something is recieved from php
},
//on error
error: function(){
//bad request
}
});
}
</script>
You can use <form> to send data
<form action="yourpage.php" method="post">
//form contents
<input type="submit" value="Submit">
</form>
The action URL specifies the URL of the page to which your data has to be send.

PHP Post to a div on main html page - So it can be parsed by Javascript

I have PHP code which successfully gets the contents of a directory on my server.
I wish to then write this array to a specific div on my main html page (so that I can parse this later and use this information further)
Currently my PHP navigates me away from my current page to write this array which I want to prevent.
Furthermore I wish to do all of the PHP work on a button click, and return the values on the main html page after.
How can I do this???
My button on my html page is as follows:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
And my PHP code looks like this to carry out the work:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
}}
I have an array: "IfPresentArray" which I then wish to write to my main html page:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
Any help would be greatly appreciated as I am very new to PHP.
Thanks in advance
You need to use AJAX techniques to do this. Use a Javascript framework like jQuery to react to the button click, make a request to your PHP script, and then update the contents of the div.
See http://api.jquery.com/click/ for handling clicks, and http://api.jquery.com/jQuery.ajax/ for making the request.
Good luck!
You will need to use an ajax call. This allows your to click some div, send something to the server, receive a response and display an output in many different formats.
You can either reference the jQuery library in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
or just download it and save it whereever
Here is a basic ajax call:
<script>
$(document).ready(function(){
$('#someval').click(function(){
var content = $('#somecontenttoadd').val; //this could be many things... etc(.text, .html)
$.ajax({
type:'post',
url: 'PHP_Function.php',
data: 'action='+content,
success: function(resp){
$('#somediv').html(resp); //lets put the information into a div
//this could be anything response format like .val or .text instead of .html
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
HTML -- you can get rid of the tags and just use the id of the object.
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" id="someval"/>
As others said, AJAX is the solution, I will give you the code that works for me, so that you have an exact starting point.
As I understand you have a separate html page and a php file that includes your function.
In order to make this work you will have to implement a function with an AJAX call.
This should be placed in a javascript file and will be invoked after the form submit button is clicked on the html page.
The AJAX call will then invoke your php function, get the response data back from php.
The javascript function will update the html page in the end.
You will need three files:
main.html
script.js
function.php
Let me replace my original answer with a full example of the three files.
main.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="myForm" method="post" action="function.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</form>
<div class="modal-footer">
<button type="submit" form="myForm" class="btn btn-primary" id="SaveButton">Submit</button>
</div>
<div id="resultbox">
</div>
</div>
</body>
</html>
Here we included jQuery, our own javascript and bootstrap just to look better. the form action is our function.php, the form 'id' is used in our jQuery code. the "result box" box will display the response.
script.js
$(function(){
$("#myForm").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
//display data...
$("#resultbox").html(data.name).show;
}
});
return false;
});
});
this will override the default form submit behavior. I had a typo here in the original answer, I fixed it. url and data are taken from the html form, dataType is set to json, because we expect a json back.
function.php
<?php
echo json_encode(array('name' => $_POST['name']));
Our php code is just one line, we build an array and return it as json. You can then used in jQuery, just like any other json, as shown in the above code.

How to make a search form using jquery and razor

I have made an CRUD application using webmatrix. I am using jquery and razor syntax. As I am still learning, took me long to figure out how to use jquery and implement it in my asp.net.
Below is the code I have done:
$('#grid').click({
function () {
$.ajax({
type: "POST",
//javascript code here
</script>
</head>
<body>
input type="text" name="fname"><<input type="button" value="Submit form">
<div id="grid" class="ui-widget">
#RenderPage("~/Partials/Recipient.cshtml")
</div>
I am interested in a way where when I click the submit button the value in my text box is posted to my Recpient.cshtml and executed, Then it is rendered underneath the search.
I am stuck here where I need to post the input value to Partials/Recipient.cshtml.
First you configure your ajax call (which would send the value of your fname input field as a POST parameter to your Recipient.cshtml script), then process Recipient.cshtml output on success.
It should look like:
$.ajax({
url: "Partials/Recipient.cshtml",
type: "POST",
data: { fname: $('input[name$="fname"]').val() }
success: function(ajaxoutput)
{
//dosomething();
}
});
More info: http://api.jquery.com/jQuery.ajax/

Categories