Send simple Ajax request to Python via JavaScript - javascript

I am new to python and I am trying to send a request to a python script with a machine learning model. I would like to get back the result of the model as a response in Ajax. My GUI is in basic HTML, CSS (no framework). How can I send the JSON data to python and get back the result in JavaScript? Below is my code...
My code
$(document).on('submit', '#form', function(e) {
e.preventDefault();
e.stopPropagation();
var form_data = new FormData(this);
form_data.append('subcounty', $('#subcounty_search').val());
form_data.append('area', $('#area').val());
$.ajax({
url: 'add.php',
type: 'post',
data: form_data,
contentType: false,
processData: false,
cache: false,
success: function(data) {
var xml = new XMLHttpRequest();
xml.open("POST", "tier match/run.py", true);
xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xml.onload = function() {
var dataReply = JSON.parse(this.responseText)
alert(dataReply)
}
var dataSend = JSON.stringify({
'home_type': $('input[name="home_type"]:checked').val(),
'residence_type': $('input[name="residence_type"]:checked').val(),
'bedrooms': $('#bedrooms').text(),
'bathrooms': $('#bathrooms').text(),
'occupancy': $('#occupancy').text(),
'swimming': encodeHomeFeatures($('input[name="swimming"]:checked').val()),
'wifi': encodeHomeFeatures($('input[name="wifi"]:checked').val()),
'tv': encodeHomeFeatures($('input[name="tv"]:checked').val()),
'workers': encodeHomeFeatures($('input[name="workers"]:checked').val()),
'wheelchair': encodeHomeFeatures($('input[name="wheelchair"]:checked').val()),
'parking': encodeHomeFeatures($('input[name="parking"]:checked').val()),
'gym': encodeHomeFeatures($('input[name="gym"]:checked').val()),
'kids': encodeHomeFeatures($('input[name="kids"]:checked').val()),
'security': encodeHomeFeatures($('input[name="security"]:checked').val()),
'garden': encodeHomeFeatures($('input[name="garden"]:checked').val()),
'ac': encodeHomeFeatures($('input[name="ac"]:checked').val()),
'pets': encodeHomeFeatures($('input[name="pets"]:checked').val()),
'smokers': encodeHomeFeatures($('input[name="smokers"]:checked').val())
});
xml.send(dataSend)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="layer top">
<form method="POST" id="form">
<div class="content-wrap">
<div class="container p-lg-0">
<!-- start of description page-->
<div class="description-page">
<div class="row">
<div class="col-12">
<div class="section-heading ml-5">
<h4 class="heading-title"><span class="heading-circle green"></span> Give a good description of your home</h4>
</div>
</div>
</div>
<br>
<div class="section-wrapper ml-5">
<h6>Title</h6>
<div class="col-8">
<input type="text" class="form-control" id="title" name="title" placeholder="Christine's Spectacular Beach House" required>
</div>
<br>
<h6>Description</h6>
<div class="col-8">
<textarea id="description" class="form-control" name="description" rows="8" cols="30" required></textarea>
</div>
<br>
<h6>Insert an image of your house</h6>
<div class="col-6">
<input type="file" id="upload" name="upload" onchange="displayname(this,$(this))" />
<label for="upload" class="add-home-image">
<i class="fas fa-file-image"></i> Upload an image
</label>
</div>
</div>
<br><br>
<input type="hidden" name="where" id="where" value="home">
<input type="hidden" name="user" value="<?php echo $customer_id; ?>">
<div class="row">
<div class="col-6">
<div class="prev ml-5">
Previous
</div>
</div>
<div class="col-6">
<div class="submit">
<button type="submit" id="completeAddHome" style="background-color: #FD5555;" class="btn btn-danger rounded-pill ml-3">Complete</button>
</div>
</div>
</div>
</div>
</div>
</div>
<br>
</div>
</div>
<!-- end of description page-->
</div>
</div>
</form>
</div>
I was trying a Http request but it wasn't working for me. I don't know if that's an option. Don't worry about the data in the JSON, I passed it through another function. How can I send that JSON to the Python script below and get a response.
Python Script (run.py)
import ml
house_features = [0,0,0,0,1,1,2,1,4,0,0,0,0,0,0,0,0,1]
tier_prediction = ml.knn_prediction(house_features)
print(tier_prediction)
This script calls the ML model below which is a script called 'ml.py'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix
def knn_prediction(features):
#house_features = [0,0,0,0,1,1,2,1,4,0,0,0,0,0,0,0,0,1]
data = pd.read_csv('/Users/Mariwa/.bitnami/stackman/machines/xampp/volumes/root/htdocs/HomeExchange/tier match/home_tier_dataset.csv')
X = data.iloc[:,:-1].values
Y = data.iloc[:, 18].values
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.9)
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
classifier = KNeighborsClassifier(n_neighbors=5)
classifier.fit(X_train,Y_train)
y_pred = classifier.predict(X_test)
check_value = np.array(features)
tier_prediction = classifier.predict([check_value])
tier = tier_prediction[0]
return tier

Related

Upload or Draw Signature on Laravel form

I used this https://www.itsolutionstuff.com/post/laravel-signature-pad-example-tutorialexample.html to create a signature pad. I am looking for a way to add an option to upload a signature or use the pad to draw a signature.
Here's what I wrote:
Laravel Blade Code
<form method="POST" action="{{ route('signaturepad.upload') }}">
<div class="tab-content">
<div class="tab-pane fade show active" id="draw">
<div class="col-md-12">
<label class="" for="">Draw Signature:</label>
<br/>
<div id="sig"></div>
<br><br>
<button id="clear" class="btn btn-danger">Clear Signature</button>
{{--<button class="btn btn-success">Save</button>--}}
<textarea id="signature" name="signature" style="display: none"></textarea>
</div>
</div>
<div class="tab-pane fade" id="upload">
<label class="" for="">Upload Signature:</label>
{{--<div class="form-group"></div>
<input type="file" name="file" id="file" required>--}}
{{--<button type="submit">Submit</button>--}}
</div>
<button class="btn btn-success">Save</button>
</div>
</form>
Javascript
<script src="{{ asset('js/pages/jquery.signature.js')}}"></script>
<script type="text/javascript">
var sig = $('#sig').signature({syncField: '#signature', syncFormat: 'PNG'});
$('#clear').click(function(e) {
e.preventDefault();
sig.signature('clear');
$("#signature").val('');
});
</script>
Controller
if(!empty($request->input('signature')) || (!empty($request->input('file')))) {
echo $request->signature;
echo $request->file;
dd('passed');
//$folderPath = public_path('uploads/');
//$data_uri = $request->signature;
//$encoded_image = explode(",", $data_uri)[1];
//$decoded_image = base64_decode($encoded_image);
//$file = $folderPath . uniqid();
//file_put_contents($file, $decoded_image);
return view('dashboard');
} else {
//dd('Signature is empty.');
return back()->withErrors(['msg', 'Signature Empty']);
}
Drawing the Signature works when one of the file uploads is commented out. When both are active they don't post and both don't work. My question is how do I work with both where one can either draw or upload the signature. I have tried if statements in the controller to no avail.
Thanks in Advance!

how to push multivalues from many element with same class or id in ajax

I have created a form , that user can append the additional column that need to that form, for example I have column name in the form , if people want to add more column name , they just press the add button , and then select element for the column name and it will be added, so it will have 2 select element with same class, but the problem is , I dont know how to send the data with ajax so django views that can get the data.Every time that I try to print the result , it will print as [] which means: failed to push the data
here's the code
html
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<form class="form-horizontal style-form" action="#">
<div class="form-group">
<label class="control-label col-md-3">Database Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id = "tableselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
<!-- <li></li> -->
{% for table in obj2 %}
<option value = "{{table}}" >{{ table }}</option>
{% endfor %}
<!-- <li>Dropdown link</li> -->
</option>
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Table Name</label>
<div class="col-md-4">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select id="dataselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick="return appendBox()">Add</button>
<label class="control-label col-md-3">Column Name</label>
<div class="col-md-4" id ="test">
<div class="btn-group">
<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;">
</select>
</div>
</div>
</div>
<div class="form-group">
<button class="btn btn-theme" onclick=" return appendFilterBox()">Add</button>
<label class="control-label col-md-3">Filter</label>
<div class="col-md-4" id="filtbox">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<select class="conditionselect" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</select>
<select class="operator" style="width:120px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
<option> > </option>
<option> < </option>
<option> ≥ </option>
<option> ≤ </option>
<option> = </option>
</select>
<input class="parameter" type="text" style="width:150px;background-color:white;height:30px;font-size:15px;text-align-last:center;">
</input>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-4" id="showquery">
<div class="input-group bootstrap-timepicker">
<div class="btn-group">
<button id="result" class="btn btn-theme" type="submit" style="height:30px;width:100px;" onclick="return showQuery()">Show</button>
<button id="export" class="btn btn-theme" type="Export" style="height:30px;width:100px;" onclick="return ExportFile()">Export</button>
</div>
</div>
</div>
</div>
<div id="query_result">
</div>
</form>
script to append the box
<script>
function appendBox()
{
$('#test').append('<select class = "columnselect" style="width:425px;background-color:white;height:30px;font-color:red;text-align-last:center;"></select>')
return false
}
</script>
<script>
function appendFilterBox()
{
$('#filtbox').append('<select class="columnselect" style="width:125px;background-color:white;height:30px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:2px"></select><select class="operator" style="width:125px;background-color:white;height:3 0px;font-size:15px;text-align-last:center;margin-top:5px;margin-right:3px"><option> > </option><option> < </option><option> ≥ </option><option> ≤ </option><option> = </option></select><input type="text" class="parameter" style="width:150px;background-color:white;height:30px;font-size:15px;"></input>')
return false
}
</script>
Ajax to send the data
<script>
$(document).ready(function() {
$("#result").click(function () {
var urls = "{% url 'polls:load-query' %}";
var table = $('#dataselect').val();
data = {
'name' : [],
'table': table,
'condition': []
};
$('#column-name .columnselect').each((idx, el) => data.name.push($(el).val()));
$('#filtbox .input-group').each((idx, el) => {
condition = {
'column' : $(el).find('.conditionselect').val(),
'operator' : $(el).find('.operator').val(),
'value' : $(el).find('.parameter').val()
};
data.condition.push(condition);
});
$.ajax({
url: urls,
data: data,
success: function(data) {
$("#query_result").html(data);
},
error: function(data)
{
alert("error occured");
}
});
});
});
</script>
is this the correct way to send multivalues with ajax? it seems the data didnt send properly when django want to get the data..
heres the view if you guys curious
def list_all_data(request):
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('', '', sid='') #ip port and user and password i hide it for privacy
conn = cx_Oracle.connect(user=r'', password='', dsn=dsn_tns)
c = conn.cursor()
print(request.GET.getlist('condition'))
data_name = request.GET.get('name',1)
table_name = request.GET.get('table',1)
column = request.GET.get('condition', {}).get('column', 1)
print(column)
operator = request.GET.get('condition', {}).get('operator', 1)
print(operator)
value = request.GET.get('condition', {}).get('value', 1)
print(value)
c.execute("select "+data_name+" from "+table_name+" where "+column + operator+"'"+value+"'")
c.rowfactory = makeDictFactory(c)
columnalldata = []
columnallname = []
for rowDict in c:
columnalldata.append(rowDict[data_name])
columnallname.append(data_name)
context = {
'obj4' : columnalldata,
'column_name' : columnallname
}
return render(request,'query_result.html',context)

Google Book API

I want to iterate over the items array that the google books API provide and print the result inside a div but somehow I am not able to do so. This is what I've written till now.
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
<!--something seems wrong here-->
<h3 class="title"></h3>
<h4 class="author"></h4>
<img src="" alt="" class="thumbnail">
</div>
</div>
<script>
function function2(){
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q="+result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res){
$.each(res.items,function(i,item){
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
<!--want to iterate over each element in items array and print it-->
$('.title').text(title);
$('.author').text(author);
$('.thumbnail').attr('src',thumb);
})
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
Your current code replaces the previous data with the current data on each iteration.
The easiest way to do what you want should be to build new elements and append them to your "result" div as shown below.
I would also recommend validating the data. Some queries I tested with returned books with no covers or authors.
function function2() {
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q=" + result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res) {
$.each(res.items, function(i, item) {
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
var elTitle = $('<h3 class="title"></h3>').html(title),
elAuthor = $('<h4 class="author"></h4>').html(author),
elThumb = $('<img src="" alt="" class="thumbnail">').attr('src', thumb);
$('#result').append(elTitle, elAuthor, elThumb);
})
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
</div>
</div>
</body>

RSA Encryption using PHP and Javascript

I am new to JavaScript and wanted to know how to display to text-box from the below code. I am having a hard time to transferring the variable encrypted info to a text-box using JavaScript. If that's not possible then how can I display the information from $('#feedback').html(data); to the textbox.
<script>
function encrypt() {
var publickey = "<?=publicKeyToHex($privatekey)?>";
var rsakey = new RSAKey();
rsakey.setPublic(publickey, "10001");
var enc = rsakey.encrypt($('#plaintext').val());
$.get('index.php?encrypted='+enc, function(data) {
var encryptedinfo = $('#feedback').html(data);
encryptedinfo.value;
});
return;
}
</script>
<div class="row-fluid">
<div class="span4">
<form class="form-horizontal" method="post">
<div class="control-group">
<label class="control-label" for="inputEmail">Plaintext</label>
<div class="controls">
<input type="text" name="plaintext" id="plaintext" placeholder="enter something">
</div>
</div>
</form>
</div>
<div class="span4">
<button type="button" class="btn btn-primary" onclick="encrypt()">Encrypt</button>
</div>
<br/>
Assuming you have the encrypted value in the data, you can simply use $("#plaintext").val(data).

saving inputs from pagedown editor in the database

I am using pagedown editor to replace textarea in an app i'm building but when i get sample codes as input from the editor and save it in the database, querying it out gives the result without any formatting.
I was expecting the result to the same as the preview of pagedown editor.
this is the form
{{Form::open(array('url'=>'profile/askquestion'))}}
<div class="form-group">
<label for="inputEmail" class="control-label">Title</label>
<div class="">
<input type="text" class="form-control" id="inputEmail" name="title" value="{{ Input::old('title') != NULL ? Input::old('title') : '' }}" placeholder="What's your programming question? Be specific." autofocus>
<span class="badge alert-danger">{{ ($errors->has('title') ? $errors->first('title') : '') }}</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="control-label"></label>
<div class="wmd-panel1">
<div id="wmd-button-bar-second" class="pagedown-swag"></div>
<textarea class="wmd-input form-control" name="body" id="wmd-input-second" rows="10"></textarea>
<span class="badge alert-danger">{{ ($errors->has('body') ? $errors->first('body') : '') }}</span>
</div><br ><hr>
<div id="wmd-preview-second" class="wmd-preview"></div><hr>
</div>
<div class="form-group">
<div class="">
<button type="submit" class="btn btn-primary pull-right">Post Your Question</button>
</div>
</div>
{{Form::close()}}
code for saving in the database
public function postAskquestion(){
$registerData = Input::all();
$registerRules = array(
'title' =>'required',
'body' =>'required',
);
$registerValidator = Validator::make($registerData,$registerRules);
if($registerValidator->fails()) {
return Redirect::back()->withInput()->withErrors($registerValidator);
}
if( $registerValidator->passes()) {
$question = new Question();
$question->title = Input::get('title');
$question->description = Input::get('body');
$question->user_id = Auth::user()->id;
$question->save();
return Redirect::to('/')->with('alertMessage',"question posted successfully.");
}
}
code for querying the contain
Route::get('question/{id}/{slug}', function ($id, $slug) {
$data['question'] = Question::find($id);
return View::make('site.question')->with($data);
});
code for displaying the contain
<div id="wmd-preview" class="wmd-panel1 wmd-preview">{{$question->description}}</div>
Help please
I know this is old post but here is how I am doing it
I'm saving the html from wmd-preview and save it with ajax
jQuery
var value = $("#wmd-preview).html();
$.ajax({
type: "POST",
url: "path/to-your-php-file",
dataType: "html",
data: {value: value} //The first value is the variable that you're sending to PHP
})
PHP
CONNECT TO YOUR DATABASE
$value = $_POST['value];
$query = mysqli_query($db,"INSERT INTO posts VALUES('$value'));

Categories

Resources