Unable to POST via JSON - javascript

I am trying to send user text from a web page to my flask app to run a script on the user text and then return a result. The problem I am having is that the text isn't appearing on the server (flask_app.py) side. Here is the .js that is supposed to be sending the text (index.js):
$(document).ready(function(){
console.log('I have loaded');
//Grab DOM elements to use later
analyzeTextButton = $("#analyze-button");
analyzeTextButton.click(function() {
// get text
text = $("#user-text").val();
//console.log(text); //This part works
$.ajax({
type: "POST",
url: "analyze",
dataType: "json",
data: {
text
},
success: function(results, results2, verbs) {
text = results.text;
console.log("Success!");
console.log(verbs);
}
})
})
Here is the Flask app that is trying to receive it. I've tried several different versions (from other Stack Overflow questions and various tutorials) but none of them work. They are labeled content1-5.
flask_app.py:
#app.route('/analyze', methods=['POST'])
def analyze():
print('You made it to analyze', file=sys.stderr) #This gets printed
content = request.get_json(silent=True)
content2 = request.json
content3 = request.get_json()
content4 = request.form.get('html', '')
content5 = request.form['contents']
print(content, file=sys.stderr) #These all return "None"
print(content2, file=sys.stderr) #Trying to make them return user text
print(content3, file=sys.stderr)
print(content4, file=sys.stderr)
print(content5, file=sys.stderr)
text = "The text is not being found"
results = my_script(content) #Run a script on whichever works
return jsonify({'results': results})
Here is the page that is trying to send the information (index.html):
<div class="row">
<form role="form" method='POST' action='#'>
<textarea class="form-control" id="user-text" name="contents" placeholder="Enter a comment"></textarea>
<button type="button" id="analyze-button" class="btn btn-default">Not Working Button</button>
<button type="submit" id="analyze-button2" class="btn btn-default">Working Button</button>
</form>
EDIT: When I look in my browser, I see that POST appears to be sending the correct string: "here+is+my+text"

data: {
text
}
should be proper JSON,it should be something like
data: {
"value":text
}
where value is key and text variable is value.

The request needed to specify that the text was html:
$.ajax({
type: 'POST',
url: "analyze",
data: {html:text},
dataType: 'json',
success: function (ret) {
alert('JSON posted: ' + JSON.stringify(ret));
}
});
On the flask app the request can be read with this line:
content4 = request.form.get('html', '')

Related

How to connect flask to ajax (retrieve data without having to reload entire page)

Goal : My code attempts to carry out the following steps : the first works, but I can't figure out how to make the POST ajax call in the second step work:
When I upload an image, it is displayed on the page.
When I click the Get prediction button, I want the result of the predict() function to be displayed in the <p> tag while the image remains on the page (i.e, without reloading the page)
I've read that AJAX is used to update parts of a web page without having to reload the entire page, but I can't seem to get it to work (Answers to a similar question did not work)
What the following code is doing instead : when I click Get prediction button, the alert is displayed (used for debugging purposes) but the result of the predict() function is displayed in a new page.
#app.route('/')
def index():
# the page that is rendered first
return render_template('hello2_without_ajax.html')
#app.route('/', methods=["POST", "GET"])
def predict():
if request.method == 'POST':
file = request.files['file']
img_path = f"static/uploads/{file.filename}"
prediction = generate_prediction(img_path)
return str(prediction)
html code :
<form id="upload-file" method="POST" enctype="multipart/form-data">
<input onchange="readURL(this)" type="file" id="upload" name='file' style="display: none;" autocomplete="off" required>
<img id="blah" />
<button id="submit_btn" onclick="$('#upload').click();">Upload image</button>
<button id="result" type="submit">Get prediction</button>
<p id="msg" style=" margin-left: 200px;"> </p>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript">
$("#result").on("click", function(e) {
var form_data = new FormData($('#upload-file')[0]);
alert(form_data)
$.ajax({
type: 'POST',
url: '/',
data: form_data,
timeout: 600000,
contentType: false,
processData: false,
cache: false,
success: function(data) {
console.log("SUCCESS !!: ", data);
$('#msg').text(' Prediction is: ' + data);
},
error: function(e) {
console.log('Failuuuuure!!')
console.log("ERROR : ", e.responseText);
alert("ERROR : " + e.responseText);
}
});
});
</script>
First, in Ajax you are making a call to '/' url which directs you to the index route not the predict route, so you need to add change the url for predict route
#app.route('/predict', methods=["POST", "GET"])
def predict():
And in Ajax you need to call /predict:
$.ajax({
type: 'POST',
url: '/predict',
In your html you need to add type="button" attribute for both buttons not not type="submit".

upload a form's file and text data to PHP using jQuery and AJAX

Good morning. I'm trying to make the form submission of a message more fluid avoiding the reload of the page for the sending of it. Since the message may be text or image, I need to send both of them to a PHP page for upload. I'm using this code in the html page:
<form id="newmessage" enctype="multipart/form-data">
<textarea form="newmessage" id="messagetext" name="messagetext" ></textarea>
<input type="submit" name="submit" value="send" onclick="return newMessage();">
<input type="file" accept="image/*" id="image" name="image">
</form>
<script>
function newMessage(){
var messagetext = document.getElementById("messagetext").value;
var image = document.getElementById("image").value;
$.ajax({
type:"post",
url:"new_message.php",
data:
{
"messagetext" :messagetext,
"image" :image,
},
cache:false,
success: function(html) {
document.getElementById("messagetext").value = "";
}
});
return false;
}
</script>
As you can see, I'm allowing users to type in the textarea or upload a file. When they submit the form, the newMessage() method is invoked and sends image and messagetext to new_message.php, which process them:
// new_message.php
$messagetext = $_POST["messagetext"];
$image = $_FILES["image"]["tmp_name"];
if((!empty($messagetext) || isset($image))) {
if(!empty($messagetext)) {
// create text message
} else if(isset($image)) {
// create image message
}
}
When I write a text message it works perfectly, but it doesn't send anything if it's image. Maybe the image variable in AJAX is not taking the file properly. I excuse if this question is unclear, but I'm a beginner in StackOverlow and I'm open to edits. Thanks for all replies.
can you try this. you don't need to worry about the file and message in textarea. Make sure you have added jQuery.
$("#newmessage").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "new_message.php",
type: "POST",
data: formData,
success: function (msg) {
document.getElementById("messagetext").value = "";
},
cache: false,
contentType: false,
processData: false
});
return false;
});

AJAX to PHP without page refresh

I'm having some trouble getting my form to submit data to my PHP file.
Without the AJAX script that I have, the form takes the user through to 'xxx.php' and submits the data on the database, however when I include this script, it prevents the page from refreshing, displays the success message, and fades in 'myDiv' but then no data appears in the database.
Any pointers in the right direction would be very much appreciated. Pulling my hair out over this one.
HTML
<form action='xxx.php' id='myForm' method='post'>
<p>Your content</p>
<input type='text' name='content' id='content'/>
<input type='submit' id='subbutton' name='subbutton' value='Submit' />
</form>
<div id='message'></div>
JavaScript
<script>
$(document).ready(function(){
$("#subbutton").click(function(e){
e.preventDefault();
var content = $("#content").attr('value');
$.ajax({
type: "POST",
url: "xxx.php",
data: "content="+content,
success: function(html){
$(".myDiv").fadeTo(500, 1);
},
beforeSend:function(){
$("#message").html("<span style='color:green ! important'>Sending request.</br></br>");
}
});
});
});
</script>
A couple of small changes should get you up and running. First, get the value of the input with .val():
var content = $("#content").val();
You mention that you're checking to see if the submit button isset() but you never send its value to the PHP function. To do that you also need to get its value:
var submit = $('#subbutton').val();
Then, in your AJAX function specify the data correctly:
$.ajax({
type: "POST",
url: "xxx.php",
data: {content:content, subbutton: submit}
...
quotes are not needed on the data attribute names.
On the PHP side you then check for the submit button like this -
if('submit' == $_POST['subbutton']) {
// remainder of your code here
Content will be available in $_POST['content'].
Change the data atribute to
data:{
content:$("#content").val()
}
Also add the atribute error to the ajax with
error:function(e){
console.log(e);
}
And try returning a var dump to $_POST in your php file.
And the most important add to the ajax the dataType atribute according to what You send :
dataType: "text" //text if You try with the var dump o json , whatever.
Another solution would be like :
$.ajax({
type: "POST",
url: "xxxwebpage..ifyouknowhatimean",
data: $("#idForm").serialize(), // serializes the form's elements.
dataType:"text" or "json" // According to what you return in php
success: function(data)
{
console.log(data); // show response from the php script.
}
});
Set the data type like this in your Ajax request: data: { content: content }
I think it isnt a correct JSON format.

Use AJAX to upload a file, process, and return a result to Javascript using Flask

I've figured out how to upload a file using AJAX and Flask such that the page doesn't refresh and the file is uploaded to the server in some specified directory.
In the Python method (upload()), I want to process the filename with some regex and return an array to the Javascript file.
Do I still return render_template(index.html), even if I'm trying to request an array?
HTML (index.html)
<form id="upload-file" role="form" action="sendQuestions" method="post" enctype="multipart/form-data">
<div class="modal-body">
<label for="file"><b>Upload packet here</b></label>
<input type="file" name="file">
<p class="help-block">Upload a .pdf or .docx file you want to read.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="upload-file-btn" type="button" class="btn btn-primary" data-dismiss="modal" value="Upload">Upload</button>
</div>
</form>
Javascript
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '/uploadajax',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: false,
success: function(data) {
console.log('Success!');
},
});
});
});
Python (Flask)
#app.route('/uploadajax', methods=['POST'])
def upload():
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return render_template('index.html')
I'm playing around with adding this AJAX call in the Javascript after the $.ajax{} part, but did I do it right? I'm not sure if I can call the same Python method twice in one Javascript function, or if there's an entirely better way to do this.
ajaxRequest = ajaxFunction()
ajax.onreadystatechange = function() {
if (ajaxRequest.readyState === 4) {
if (ajaxRequest.status === 200) {
alert(ajaxRequest.responseText) //I want the Python to put the array into this ajaxRequest.responseText variable, not sure how.
}
else
alert('Error with the XML request.')
}
}
ajaxRequest.open("GET", 'uploadajax', true);
ajaxRequest.send(null);
Any help? Thanks.
You don't say what you want to achieve (hide some div, scroll window ...), and that's a main problem. To sum what should be done :
Don't return
return render_template('index.html')
but fe. if you want to notify the user about the upload status, make status for this call like
return Response('OK')
or other status - NOTOK or something.
Then in the js :
success: function(data) {
console.log('Success!');
},
manipulate the response
if (data == 'OK') {
alert ('YAY, FILE UPLOADED');
};

post method not working

I want to submit form data using post using ajax because in form post after submit it is redirected to a new page.
<form id="myContactForm">
<p>
<label for="byour_name">Your name</label><input type="text" name="byour_name" value="" id="byour_name">
</p>
<p>
<label for="byour_email_address">Your email address</label><input type="text" name="byour_email_address" value="" id="byour_email_address">
</p>
<p>
What's on your mind?<br>
<textarea name="Message" rows="10" cols="25"></textarea>
</p>
<p>
<input type="submit" value="Send it!" onClick="sendMail()">
</p>
</form>
function sendMail() {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),
success: function( response) {
alert(response);
},
error: function() {
alert('failure');
}
});
}
Every time I make request error function is executing.I am writing app on google app engine. I am keep getting this error:
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
My post request handler is:
def post(self):
Content = self.request.get("Message")
byName = self.request.get("byour_name")
byEmailAddress = self.request.get("byour_email_address")
gmailUser = 'id#gmail.com'
gmailPassword = 'password'
dataSend = byName
mail.send_mail(sender = gmailUser,
to = gmailUser,
subject ="Email Sent By : "+ byName + "#" + byEmailAddress,
body = Content)
self.response.out.write(byEmailAddress)
And after I click submit button URl changes to:
http://localhost:8080/?byour_name=username&byour_email_address=userEmail#gmail.com%40gmail.com&Message=mlm%0D%0A#contact
as I am making a get request can someone help me..But how post request changes to get request.
You're not preventing the default submit. Either return false from your sendMail function, or take the event as a parameter and call preventDefault() on it.
Please remove form tag and the get the desired values by id and then use ajax method. Because may be ajax post and form request method are conflicting. I think form has default get method as you said earlier may be that's the reason whenever you click on submit first ajax post make request soon after form get method and may be that's the reason the error is thrown by your server.
I think I know what your trying to do , to fix this you can do the following:
remove onclick="sendMail()"
and change your JavaScript function to something like:
$('#myContactForm').submit(function () {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),success:
function( response) {
alert(response);
},
error: function(){
alert('failure');
}
});
});

Categories

Resources