Get JSON response in Pug - javascript

I set up some APIs in my index.js file to do actions such as create a new post (POST request). I handle it in my Pug file with form elements, like so:
form(method='post' class="addPostForm" target="invis" action='/api/addPost')
input(type='text' class="addPostInput" name='content' placeholder='Post...')
input(type='submit' class="submitPostBtn" value='Add!')
However, I need to get the JSON response from my API (e.g. the success, status, etc.) This data would be used to check if a user has successfully added a post, and if so, adjust the Pug rendering accordingly. How can I do this? I've heard about Ajax, but is that the only way?

Related

Tabulator save table to server

Tabulator get an option to parse table from remote server like ajaxURL:"https://mysite/data.json" and download table data as json.
But don't let to upload json data to same or another server.
How can I do the upload function to my table?
This is a very open ended question as that depends on which type of server you are using.
The standard method would be to make an AJAX request to the server, usually a POST or PUT request depending on whether you were creating or updating data.
You would retrieve the data from tabulator using the getData method, which return s an array of row data objects.
var data = table.getData()
You can then use an ajax library of your choice. Browsers come with the built in Fetch API or you could use a 3rd party library like Axios
How you send the data to the server is up to you as you will have to put the code in on the server to process it, so you will set the property names etc that the data will need to be set against in the request.

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)

I'm trying to send a JSON object from client to server and receive a response but all the approaches I find are either inadequate or overkill

I'm in a situation where I'm not sure what is the correct way of doing this. I'm trying to take a large json file, send it to the server, process and reorder it, and then send it back to the client. I don't want to store any data in a database. I know there's the HTTP GET verb, but the amount of data I would be inputting would be longer than the max length URI. I also read that you shouldn't try to do this with a HTTP POST either.
I looked into WebSockets as well but to me it appears to be overkill. I would only need the socket for the time that it takes to do the computations, then I would close it. Also I want to share the data with only the client who sent it to me.
Does any one have recommendations as for what to do. Maybe just a push in the right direction with a few links I can read. I'm really looking for something that runs down the middle of these two methods.
Why don't you just use a HTTP POST request? Taken from an info box on
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
> Request has body Yes
> Successful response has body Yes
> Safe No
> Idempotent No
> Cacheable Only if freshness information is included
> Allowed in HTML forms Yes
As you see, a HTTP POST request is used for sending data to the server, and if the POST request was successful, the server sends data back to the client. Perfect for your situation, I think.
A POST request doesn't have to be used within a HTML form; you could use XHR, AJAX, the fetch API, or any other way you can find to send the server a POST request. And yes, you could send JSON data with it.
If you need more convincing:
When the POST request is sent via a method other than an HTML form — like via an XMLHttpRequest — the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions:
Annotation of existing resources
Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
Adding a new user through a signup modal;
Providing a block of data, such as the result of submitting a form, to a data-handling process;
Extending a database through an append operation.
Notice that there, it said that a POST request can be used to provide a block of data to a data-handling process.
Hope this helps you. :)

Insert data into DB with Symfony2 via JavaScript, without a form

I'm currently working on a Symfony2 project where a user can comment on parts of a webpage via contenteditable spans. I now want to save these comments, that are assembled in an array of JSON objects, into the database, with a reference to the page and the user id. This is where I'm stuck.
What steps are needed to put the data from the JavaScript code into the specific DB table?
I already created a Comment class in the Entity folder. And based on this
answer I added the following code in my saveComment() in JavaScript:
$.post('saveComments.php', {
page_id : getPageId(),
user_id : getUserId(),
comments : getJSONcomments(),
});
What next...?
Ok, let's create a saveComments.php ... but where in the bundle? Or could this be done with a Controller? If so, how and what would I need to replace the url ("saveComments.php") in the $.post(...) call with?
Don't post to a PHP page as this breaks the Symfony 2 model. Instead post to a route, like save/comment or along these lines.
Configure the route to point to an action in a controller.
Implement the controller and the action so that it does not take any parameters. Inside the action unpack the posted data the usual PHP way using (because you won't have a form to bind your data to):
$_POST
Just to get it working, echo a var_dump() to the console and see what you get. This is an example on how to write to the console.
Decode the JSON data with the serializer.
The decoded data will be a simple associative PHP array. Interpret the data you received and act accordingly (don't forget to handle security and all that stuff, too -- you don't want to open up security holes through AJAX).
Best is, you check that the route you chose falls into the security tier you need and probably already have configured in the Symfony 2 application. This way you don't need to handle security manually in the action.
Once this is done return an HTTP response with code 200 OK.
return new Response('', Response::HTTP_OK); // no response text at all
If there's any error reply with a 500 class HTTP server error:
return new Response('', Response::HTTP_INTERNAL_SERVER_ERROR); // 500
Also, don't forget to handle client-side errors with the .error() method.

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