Flask - Request.args.get not getting parameters from AJAX call - javascript

I have a Flask web app that receives AJAX statuses/requests via request.args.get however one of my requests aren't being read by my Flask app. The other status status works fine, but doorStatus does not.
The data is successfully sent by AJAX since I can see the reqeust when I go to dev tools > network in my browser. Am I missing something?
from flask import Flask, request, jsonify
import serial
import time
app = Flask(__name__)
ser = serial.Serial('/dev/ttyACM0', 9600)
# {{url}}/led?status=on
#app.route('/', methods=['GET'])
def led():
status = request.args.get('status')
if status == "on":
exteriorOn = 'H'
exteriorOnEncode = exteriorOn.encode()
ser.write(exteriorOnEncode)
return jsonify({"message": "Led successfully turned on"})
elif status == "off":
exteriorOff = 'C'
exteriorOffEncode = exteriorOff.encode()
ser.write(exteriorOffEncode)
return jsonify({"message": "Led successfully turned off"})
else:
return jsonify({"message": "Not a valid status"})
doorStatus = request.args.get('doorStatus')
if doorStatus == "open":
doorOpen = 'L'
doorOpenEncode = doorOpen.encode()
ser.write(doorOpenEncode)
return jsonify({"message": "Door successfully opened"})
elif doorStatus == "closed":
doorClosed = 'N'
doorClosedEncode = doorClosed.encode()
ser.write(doorClosedEncode)
return jsonify({"message" : "Door successfulled closed"})
else:
return jsonify({"message" : "Not a valid status"})
JS
$(document).ready(function() {
$('#openDoor').on('click', function(e){
let doorStatus;
if($(this).text() == 'OPEN') {
$(this).text('CLOSE')
doorStatus = 'open';
} else {
$(this).text('OPEN');
doorStatus = 'closed';
}
$.ajax({
url: '/led',
method: 'GET',
data: {doorStatus},
success: function(result) {
console.log(result);
}
});
e.preventDefault();
});
$('#exteriorBtn').on('click', function(e){
let status;
if($(this).text() == 'Exterior') {
$(this).text('Turn Off')
status = 'on';
} else {
$(this).text('Exterior');
status = 'off';
}
$.ajax({
url: '/led',
method: 'GET',
data:{status},
success: function(result) {
console.log(result);
}
});
e.preventDefault();
});
});

When you GET or POST data, it needs to have a name and value pair.
GET Example:
http://www.nowhere.place/webpage.html?status=open
You can see the name status and it's value open.
See more: https://api.jquery.com/jquery.ajax/
data
Type: PlainObject or String or Array
Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL
Plain Object Example:
data: { status: "OPEN" }
String Example:
data: encodeURIComponent("status=OPEN")
Array Example:
data: [ "OPEN" ]
So for your code, I would advise:
$('#openDoor').on('click', function(e){
e.preventDefault();
var door = { status: "" };
if($(this).text() == 'OPEN') {
$(this).text('CLOSE');
door.status = 'open';
} else {
$(this).text('OPEN');
door.status = 'closed';
}
$.ajax({
url: '/led',
method: 'GET',
data: door,
success: function(result) {
console.log(result);
}
});
});

Related

AJAX Callback Not Showing Success Message - ASP.NET MVC C#

I have some AJAX code in my JavaScript which is not showing any success or failure alert.
function AttemptHouseViewingAppointment(house) {
var imgOfHouse = $(house).attr("value");
$.ajax({
type: "POST",
url: '#Url.Action("AttemptHouseViewingAppointment", "Viewing")',
dataType: "json",
data: ({
userId: #Model.UserId,
appointmentKey: '#Model.Key',
chosenHouse: imgOfHouse
}),
success: function (data) {
alert(data);
if (data.success) {
alert(data.message);
} else { alert(data.Message) }
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
The above function is called when I click an image on the screen. This part works fine as I have set a breakpoint on my ASP controller and I can see the relevant action being called. C# code below:
public ActionResult AttemptHouseViewingAppointment(int userId, string appointmentKey, int chosenHouse)
{
string selecteHouseName = $"./house-code-icons/{chosenHouse}.png";
var house =
_ctx.houses.Where(x => x.HouseID == userId && x.Icon == chosenHouse)
.FirstOrDefault() ?? null;
if(house != null)
{
var member = _ctx.User.FirstOrDefault(x => x.Id.Equals(userId));
_ctx.Appointments.Add(new ViewingModel
{
House = chosenHouse,
UserId = userId
});
_ctx.SaveChanges();
return Json(new { success = true, message = "Appointment Confirmed!" });
}
else
{
return Json(new { success = false, message = "Sorry, a booking has already been made!" });
}
}
Even though, the return Json lines are being hit and returned to the page, there is no alert popup on my page to let user know if success or not. Please let me know if any questions.
Thanks
Add the done function to the end of Ajax
$.ajax({
.
.
.
}).done(function( response ) {
alert(response);
...
});

trouble returning json from python to javascript with ajax

I'm sending articleUrl from my .js to my python function, which works fine. I then want my python function to return pubscore back to the .js.
pubscore prints fine in the .py, but then I get "Uncaught ReferenceError: pubscore is not defined at Object.myFunction [as success] (background.js:41)". Line 41 is var myPubscore = pubscore in the .js.
background.js
$.ajax({
type: 'POST',
url: `${url}/buttoncolor`,
data: articleUrl,
success: function urlFunction(data) {
var myPubscore = pubscore;
console.log(myPubscore);
}
})
application.py
def buttoncolor():
import json
if request.method == 'POST':
if not request.form['url']:
flash('Please enter all the fields', 'error')
else:
rurl = request.form['url']
...
pubscore = pub_tuple[8]
print(pubscore)
return json.dumps(pubscore)
else:
strscore = str(pubscore)
message = {'greeting': strscore}
return jsonify(message) # serialize and use JSON headers
Suggested code that didn't work for me but could be helpful to someone else
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "articleUrl") {
var articleUrl = request;
$.ajax({
type: 'POST',
url: `${url}/buttoncolor`,
data: articleUrl,
success: function(){ alert('success');
}
})
$.getJSON(`${url}/buttoncolor`,{data: articleUrl}, function(data) {
doWork(data.greetings);
});
function doWork(myPubscore){
console.log(myPubscore);
if (myPubscore > 1)
{console.log("myPubscore is more than 1")}
}
}
Please try this
function doWork(data) {
const myPubscore = data.greeting;
console.log(myPubscore)
if (myPubscore > 1) {
console.log("myPubscore is more than 1")
}
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "articleUrl") {
var articleUrl = request;
$.ajax({
type: 'POST',
url: `${url}/buttoncolor`,
data: articleUrl,
success: doWork,
error: function(e) {
console.log("error", e)
}
})
}
})

Django JSON Response to HTML Page Not Working

I have a Django project where I am trying to get AJAX working. I can't seem to send the JSON response to the HTML page. When I check the chrome console the JSON data is not returned only parses the HTML.
This is my Views.py where I have the cart logic defined:
def cart_home(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
return render(request, "carts/carts.html", {"cart": cart_obj})
def cart_update(request):
print("Hello")
product_id = request.POST.get('product_id')
if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Product is gone")
return redirect("cart:home")
cart_obj, new_obj = Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
added = False
else:
cart_obj.products.add(product_obj)
added = True
request.session['cart_items'] = cart_obj.products.count()
if request.is_ajax():
print("Ajax request")
json_data = {
"added": added,
"removed": not added,
}
return JsonResponse(json_data)
return redirect("cart:home")
This is javascript for the Ajax:
<script>
$(document).ready(function(){
var productForm = $(".form-product-ajax")
productForm.submit(function(event){
event.preventDefault();
console.log("Form is not sending")
var thisForm = $(this)
var actionEndpoint; thisForm.attr("action");
var httpMethod; thisForm.attr("method");
var formData; thisForm.serialize();
$.ajax({
url: actionEndpoint,
method: httpMethod,
data: formData,
success: function(data){
console.log("success")
console.log(data)
console.log(data.added)
console.log(data.removed)
console.log("Added", data.added)
console.log("Removed", data.removed)
var submitSpan = thisForm.find(".submit-span")
if (data.added){
submitSpan.html("<button>Remove</button>")
} else {
submitspan.html("<button>Add to Basket</button>")
}
},
error: function(errorData){
console.log("error")
console.log(errorData)
}
})
})
})
</script>
Added screenshot of Chrome Inspector (Network Tab)

Django Ajax returns whole html page

I'm trying to create live search filter,with ajax
$(function() {
$('#search-item').keyup(function() {
$.ajax({
type: "GET",
url: "/toysprices/",
data: {
'query' : $('#search-toy').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
console.log(data);
}
and my views.py
f request.method == "GET":
search_text = request.GET['query']
if search_text:
search_text = request.GET['query']
statuss = Status.objects.filter(status__contains = search_text)
else:
statuss = Status.objects.all()
return render(request, 'ajax_search.html', {'statuss':statuss})
it works correctly, but it returns whole html page, how can i make to get only part which I want to render in my template.
Returning the result with JSON will solve your problem.
For Example,
# Django view
def search(request):
if request.method == "GET":
return_array = []
search_text = request.GET.get('query') # Always put request.GET.get('param') instead of request.GET['param']
if search_text:
search_text = request.GET.get('query')
statuss = Status.objects.filter(status__icontains = search_text)
else:
statuss = Status.objects.all()
for i in statuss:
return_sub_array = {}
return_sub_array['status_name'] = i.status_name
return_array.append(return_sub_array)
return HttpResponse(json.dumps(return_array))
# Jquery function
$('#search-item').keyup(function() {
$.ajax({
type: "GET",
url: "/toysprices/",
dataType: 'JSON',
data: {
'query' : $('#search-toy').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function(data){
if(data.length > 0 )
{
console.log(data);
for (var i = 0; i < data.length ; i++) {
var obj = data[i]['status_name'];
console.log(obj)
// further logic goes here
}
}
else {
console.log("No result found");
}
},
error:function(data){
console.log('error')
console.log(data)
}
});
});
In most cases it is the url which you are using to call, assuming you have the following path in the url.py
path('Import/', views.Import, name='import'),#.....1
path('getMetaData/', views.metaData, name='metadata'),#....2
and your url: http://127.0.0.1:8000/folder/Import/ is using the first path which is showing the page, if you wish to get data from ajax from the metaData function in views.py, if you use path 2 above it will give you html, so your path should be as follows:
path('Import/getMetaData/', views.metaData, name='metadata'),#....3
You are rendering html and returning it in your view. Here's nothing to expect from this view other than html. In order to return JSON object as a response, your view should return response like this:
return JsonResponse({'statuss':statuss})

Delete a file with ajax request

I'm trying to delete a file with ajax request:
javascript:
function deleteFile(file_path)
{
var r = confirm("Sure?")
if(r == true)
{
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
method: 'GET',
success: function (response) {
alert('Deleted!');
},
error: function () {
alert('Not Deleted!');
}
});
}
}
delete_file.php :
unlink($_GET['file']);
It returns true on succes,but the file is not deleted.
Check the response in AJAX, Best is use JSON DATA to check the response:
// Default AJAX request type is GET so no need to define
$.ajax({
url: 'delete_file.php',
data: {'file' : file_path },
dataType: 'json',
success: function (response) {
if( response.status === true ) {
alert('File Deleted!');
}
else alert('Something Went Wrong!');
}
});
Do It like this in PHP:
// First Check if file exists
$response = array('status'=>false);
if( file_exists('FILE_PATH/FILENAME') ) {
unlink('FILE_PATH/FILENAME');
$response['status'] = true;
}
// Send JSON Data to AJAX Request
echo json_encode($response);
Make sure you are giving the complete path with filename to unlink() function
Try this you need to check file, give permission, then delete it
$filename = 'full absolute file path';
if(file_exists($filename)) {
#chmod($filename, 0777);
#unlink($filename);
return true;
}
As there can be two issues either the file path is not correct or the file is not having permission.
With the above code both will be checked.

Categories

Resources