Send JSON data to Flask server using JQuery .load() - javascript

I am trying to use JQuery's .load() function to send data to my Flask server and, using that, render a <div> that is loaded into the calling element. My call looks something like this:
$("#element").load(
"/get_data",
{"info": info} // this is the problem
)
However, when I try to access this data in my Flask backend, the data is of form byte-string. (Accessing with request.get_data() yields a byte-string and request.get_json() yields None).
This did not surprise me, as the same behavior occurs when I use .ajax() requests. With Ajax, I simply use data: JSON.stringify({"info":info}) and that sends a string easily read by json.loads to the Flask backend just fine. What befuddles me is when I attempt the same data packaging with .load(), the request to the server is a GET instead of a POST.
Per .load()'s documentation, "The POST method is used if data is provided as an object; otherwise, GET is assumed." I don't understand why the data being a JSON string alters the behavior of .load() this way.
I'm keen to understand this behavior, but my question is how can I send data using JQuery's .load() to a Flask backend as a POST request in form JSON, or at least readable as a json (e.g. JSON string)?

Your code should work. You have data as {"info": info}, which is an object that .load should send as a POST. Make sure you are getting a JSON mimetype object from the server. Also, make sure your Flask view accepts the POST method:
from flask import Flask, request, Response
import json
#app.route('/get_data', methods = ['GET', 'POST'])
def get_data():
payload_dict = json.loads(request.data.decode('utf-8'))
# or try payload_dict = request.json
print(payload_dict["info"])
return Response(json.dumps({"info_response": "hello"}), mimetype='application/json')
And make sure you have info defined in {"info": info}
Thought about using getJSON: https://api.jquery.com/jQuery.getJSON/ ?

Related

Alternative render of JSON response in Django depending on request origination

I'm trying to find a way how to return JsonResponse which would be either interpreted as JSON when received by Ajax success function, or will be rendered to 404 (or any other page) if will be called directly via URL.
The reason I'm looking for this is because on my website I have few places where I am using empty modal view (pop-up) which is later populated with proper HTML content by server based on Ajax request.
In return JSON to my Ajax success function I have only HTML responsible for the modal content. So, when displayed as standalone (by typing GET request url directly in browser) it is JSON object.
What I'd like to achieve is display some page in such case (directly typed url for GET request), which will inform user that he's in wrong place, but at the same time will be properly understood by Ajax.
So far I've considered two approaches:
Use POST request - this is ok, until I need to render form in modal which is then sent back, also as a POST request, to server to be somehow processed. It requires some ugly workarounds to figure out if request is to render form and send HTML back, or to process form. In this approach I can return 404 page simply using http_method_not_allowed function.
Render JSON response using return render(request, 'mytemplate', {'form_html': form_from_string}) - this requires change of Ajax request to use text dataType and some extra workarounds on JS side to extract form_html.
Is there any 3rd option to get it working as I've imagined it will work?
I'm not sure to fully understand your question, but you can use request.is_ajax() to determine if the request was made using Ajax.
It uses the header X-Requested-With to determine if the request was made from ajax context.
Example:
class MyView(View):
def dispatch(self, request, *args, **kwargs):
if not request.is_ajax():
raise Http404
return super().dispatch(request, *args, **kwargs)

Receiving AJAX Data on Cherrypy: 400 Bad Request from Javascript Post Request

I'm fairly new to web development. I am currently trying to make a post request from my javascript website to my separately hosted python code (using cherrypy), and have received a "400 Bad Request" in the console of my web browser.
I think the issue may be with the cherrypy method I took from the link shown in the code, or with "data" in the javascript code. Cherrypy works fine for everything else in my Python code (none of the other methods involve receiving data from javascript, but rather python). I finally created a stackoverflow account after being stuck on this for a while. The exact error given in the browser console is: "Post [url] 400 (Bad Request)"
Any help would be greatly appreciated.
// From the Website (Post Request):
$.ajax({
url:'relevanturl',
type:"POST",
// id, title, start_time, and end_time are strings, and userlist is an array of strings
data:{id:id, title:title, start_time:start_time, end_time:end_time, userlist:userlist},
success:function() {
},
error:function(jqXHR,textStatus,errorThrown
{alert('Exception:'+errorThrown);}
});
# The specific cherrypy method not working (I made it with help from
# this link that shows how to handle AJAX requests:
# https://stackoverflow.com/questions/3743769/how-to-receive-json-in-a-post-request-in-cherrypy
#cherrypy.expose
def add_meeting(self, data=None):
cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read(int(cl))
body = simplejson.loads(rawbody)
# For now, I'm just trying to receive the data from the website.
print(body)
The information from the link in the comments solved the problem.
How to receive JSON in a POST request in CherryPy?
The solution was to convert the data into JSON, and follow the necessary $.ajax syntax for JSON. To receive the data with CherryPy, #cherrypy.tools.json_in() must be called along with the usual "expose," and all the other relevant Python code from the link.
Thank you!

Is JSON not serialise-able over http or Django doesn't know how to read it?

I have created a couple of projects with Django.
Every time I try to send an ajax POST request from frontend to django, I have to use JSON.stringify() function, pass it inside the body of POST request and parse the JSON manually inside Django (using ujson, because of its faster).
My question is that why do I need to do this manually?

how to pass the ajax Post url with paramters to web service?

actually i have webservice running and i want to retrieve the response or output of web service (xml output) and want to show it on some web page. i am trying to give some parameters as input and sending to webservice by AJAX POST and getting some dummy response.. i have problem while sending the parameters with URL. WOULD YOU TELL ME ABOUT THE FORMAT OF AJAX POST PARAMTERS?
var params="text=text1&target=target1";
It returns some error value in response, but with the same data i am able to access with the terminal.
text=text1&target=target1 these paramters are passing as one string not different paramters
I have tried in other way also
var params='text='+text1+'&target='+target1;
but it returns nothing in response
What should I set for params value?
You can't send POST data via url query string.
You will need to either use cURL from the command line, or use a POST tool like POSTMAN to pass form data and the appropriate POST headers.
Edit: your tags suggest you're using javascript/ajax.
You can do this natively with javascript, but you'd have a significantly easier time using jQuery's $.ajax or $.post:
$.ajax({
type: "POST",
url: "http://myapp.com/someendpoint",
data: {
text: "text1",
target: "target1"
}
});

facebook - LIKE a post via ajax

I am creating a facebook wall (stream) look-a-like to put on my site.
This component will read all posts from a specific page`s wall and display them, via the graph api.
I also want the user to be able to LIKE the posts displayed on the "wall".
What I have so far is a script that uses the graph api to get the JSON list of posts and I also have a PHP file that can LIKE a post who`s ID is submitted in the post_id query string parameter, and this does work. I see the LIKE is submitted.
To call this PHP file I use jQuery ajax:
function do_likes(post_id) {
$.ajax({
type: "POST",
url:"http://www.p-art.co.il/facebook_test/action.php?post_id=" + post_id
});
Firebug doesn't show any error, but on the other hand, the LIKE is not posted.
I have been searching for several hours, but I can't find the correct way to call the PHP file, in order for the FB.api call to work.
Thank you in advance.
-Elad
With a HTTP POST, data is normally sent from form inputs with the enctype set to application/x-www-form-urlencoded format. So with an AJAX POST, we would usually send data in this format also and not as a query string parameter, which is how data is usually sent with a HTTP GET request and how you are sending data above.
if you change your code to
function do_likes(post_id) {
$.ajax({
type: "POST",
url:"http://www.p-art.co.il/facebook_test/action.php",
data : { post_id : post_id }
});
}
it should work as expected (I'm not familiar with PHP but I assume that the URL you're posting to expects data in application/x-www-form-urlencoded format). with jQuery.ajax(), if you set the data object to the key/value pairs that you want to send to the server, jQuery will take care of providing the correct enctype for you based on the HTTP request type you are using (you can override the enctype if necessary, but usually this is not required and the defaults will be what you need in the majority of cases).
Also, you may want to set a callback function to be called after the AJAX post has successfully completed. To do this add a success property to the object passed to the $.ajax() call.
It's hard to tell without seeing the source code for your action.php file but I'm guessing its not getting the users access token correctly due to it being called via AJAX.
If you can post your action.php source somewhere I should be able to help some more

Categories

Resources