Step-by-step guide: learn how AJAX sends input to your ML model for fast, accurate predictions.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Here is an example using vanilla JavaScript (without any libraries):
document.getElementById("sendButton").addEventListener("click", function() {
// Create an object to hold user input, assuming there's an input element with id "userInput"
var inputData = {
userText: document.getElementById("userInput").value
};
// Initiate an AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open("POST", "/predict", true); // '/predict' is the endpoint on the server
// Set the request header to indicate we're sending JSON data
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// Define a callback function to handle the response
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Parse and use the returned prediction result
var response = JSON.parse(xhr.responseText);
// Display the result (for example, update a div with id "result")
document.getElementById("result").innerText = "Prediction: " + response.prediction;
}
};
// Send the stringified input data to the server
xhr.send(JSON.stringify(inputData));
});
/predict) that listens for POST requests with JSON content.
// Example using Python with Flask
from flask import Flask, request, jsonify
import joblib // For loading a pre-trained model; alternatively use pickle
app = Flask(name)
// Load your pre-trained model (assumed to be stored in a file "model.pkl")
model = joblib.load("model.pkl")
// Define the /predict endpoint to handle AJAX POST requests
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json() // Get JSON data from request
user_text = data.get("userText")
// Process the input if necessary (e.g., text preprocessing)
// For instance, if using CountVectorizer or similar to transform the text
// Assuming a simple prediction scenario; the model expects proper input format (preprocessed)
prediction_result = model.predict([user_text])
// Return the prediction as a JSON object
return jsonify({"prediction": prediction\_result[0]})
if name == 'main':
app.run(debug=True)
predict method (or similar) to compute the prediction. The result is then sent back to the client.
// Continuing our Flask example with simple preprocessing and error handling
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.get\_json()
user\_text = data.get("userText", "").strip()
// Basic validation
if not user\_text:
return jsonify({"error": "Input text is required."}), 400
// Perform any necessary preprocessing here
// e.g., transforming text into a numeric vector if required by the model
processed_input = preprocess_text(user_text) // Assume preprocess_text() handles this
prediction_result = model.predict([processed_input])
return jsonify({"prediction": prediction\_result[0]})
except Exception as e:
return jsonify({"error": str(e)}), 500
def preprocess_text(text):
// Replace with actual preprocessing logic as per your model's requirements
return text.lower() // Example: simple conversion to lower-case
/predict endpoint, processes the input through the ML model, and sends back the prediction. The client then updates the UI with the returned prediction.
// Front-end HTML snippet example:
AJAX ML Model Demo
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â