using backbone to put data into rest server - javascript

I have a question.
If i have a model named Input. It contains model Invoice and Collection InvoiceDetailCollection.
I modified the backbone.js specifically create:"POST" into create:"PUT" inorder to allow PUT since my service doesn't use POST.
If i were to use Input.save() What should my server expect as a request? I mean already have set a service method to expect string since if i expect string i can't use the input.save();
What should be the right parameter i should expect on my server side if i were to use the Input.save() method of backbone.js

By default, Backbone sends application/json data and the server should expects JSON data. You'll want to decode it. I use PHP and middleware that automatically json_decode($data) and turns it into an associative array for me to manipulate.
If this isn't possible, (can't take JSON data) I think what you want is to use emulateJSON It will serialize your data and send it as application/x-www-form-urlencoded like an HTML form.
http://documentcloud.github.com/backbone/#Sync-emulateJSON

Related

Backend can't get POST from javascript fetch API [duplicate]

I'm using PHP, ExtJS and ajax store.
It sends data (on create, update, destroy) not in POST or GET. In the Chrome Console I see my outgoing params as JSON in the "Request Payload" field. $_POST and $_GET are empty.
How to retrieve it in PHP?
If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data then contains the json data is php array.
php://input is a so called wrapper.
php://input is a read-only stream that allows you to read raw data
from the request body. In the case of POST requests, it is preferable
to use php://input instead of $HTTP_RAW_POST_DATA as it does not
depend on special php.ini directives. Moreover, for those cases where
$HTTP_RAW_POST_DATA is not populated by default, it is a potentially
less memory intensive alternative to activating
always_populate_raw_post_data. php://input is not available with
enctype="multipart/form-data".
Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).
... the values will be sent as part of the request parameters as
opposed to a raw post (via docs for encode config of Ext.data.writer.Json)
UPDATE
Also docs say that:
The encode option should only be set to true when a root is defined
So, probably, writer's root config is required.

Is it safe to make a POST request with JSON data using ajax?

I'm working on web application where I need to send some data using ajax with post method. So I have two choices to send data whether in JSON format or query prams. I'm confused which should I use? and is it safe to send data in JSON format?
As #lucasreta mentioned, if you use HTTPS, it doesn't really matter either way.
Both methods are widely used. I know that Google accepts a Post request with query params and responds with a JSON object for ReCaptcha Server side validation.
Sometimes, the decision to use one or the other (or both) is dependent on how easy your chosen back-end technology makes it for you to either parse out query params or serialize JSON.
I will say that there is a general trend in using JSON in the request body as opposed to query params.
I found a couple of SO questions that are more down the lines of what you are asking...
REST API Best practices: args in query string vs in request body
REST API Best practices: Where to put parameters?

Why is my $_POST empty but file_get_contents('php://input') is not?

When I POST data to my server using a regular old form submit I can pull that data from the $_POST variable, but when POSTing JSON data via AJAX I need to access it via file_get_contents('php://input'). Why is that? In both cases I am using the POST method, are there some explicit headers I should be setting on my AJAX call? I have only ever come up against this problem on the current development server and have never had to use file_get_contents('php://input') before. Is there a server setting somewhere? Can I change this behaviour with a .htaccess?
Add this to the top of your .php file:
$_POST = json_decode(file_get_contents("php://input"), true);
so that the contents will be property decoded and available. After that, you can access individual keys as usual.
So as far as I have been able to find out, this has something to do with the way the data is received by the server - PHP can't natively parse JSON. Sending plain old JSON objects from Javascript to PHP will result in PHP not knowing what to do with the datatype, and thus it won't be able to prepopulate the appropriate global variables.
In order to get around it I added a check to my ajax wrapper function that intercepts the JSON, encodes is as a FormData object and shoots that off to the server instead.

Using Different Objects In Array Model AngularJS

I am very new to angular and this one is striking in my head a lot. So scenario is : Suppose angular http returns me model containing array of object like:
[{name:"Ankur",lastName:"aggarwal",updation_date:"23-08-2014"},{name:"xyz",lastName:"abc",updation_date:"29-08-2013"}]
Out of this updation_date is not required but coming for some reason. So is it right to update the array with third object without creation date like {name:"def",lastName:"jbc"} . Is it a good practice or array object model should be consistent?
Also what should be the approach? Update the model array first so binding take place instantly, then send it to the server or send it to server and get the updated object? Might be basic one but very new to angular and JMVC.
Is it a good practice or array object model should be consistent?
It depends , if backend expects all array entries to contain updation_date then you have no choice and are forced to add some sensible default value. However, if possible then avoid sending too much unnecessary data from backend since it impacts application performance(like data transfer, adding unnecessary logic to generate sensible default values, etc.)
Update the model array first so binding take place instantly, then
send it to the server or send it to server and get the updated object?
If the nature of your application permits reverting model value when save is unsuccessful then just go ahead with
0.Perform data validation, and make sure valid data is supplied to the backend.
1.Update model.
2.Send data to backend
3.If something bad happens then execute error handling depending on app needs
However if presenting consistent value in the GUI is uttermost importance(e.g. finance applications) then
0.Perform data validation, and make sure valid data is supplied to the backend.
1.Show some message to user like "saving"
2.Perform ajax request
3.If successful, update model, else execute error handling depending on app needs
It depend on your error handling.
As saving on the server-side might be not successful, you should take it into consideration.
My approach is to
Update angular object immediately
Then send AJAX request to server and
Wait for response. If error happen during server save, you shoulde:
revert values,
repeat AJAX
show information to user.

Pros and cons of parameterizing angular request

I'm a full-time backend developer just starting to learn angular for some of my own projects.
By default it seems angular $http requests are sent as JSON strings. I am currently overriding the transformRequest method to parameterize it like jquery. Its more convenient for my backend framework (Phalcon PHP) to receive it this way.
Before I commit to this path, are there any cons to structuring it this way? Any problems unit testing or using third-party modules?
Edit
To clarify, angular sends POST as JSON string in the body. jQuery and other frameworks I've used send as form-urlencded like:
Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21
http://en.wikipedia.org/wiki/POST_%28HTTP%29#Use_for_submitting_web_forms
Which, perhaps due to the content header populates the $_POST global in php (I assume) with the form data;
I would recommend you to stick to the JSON format and send data in JSON request body instead of key=value param pairs. You can receive JSON cleanly with Request::getJsonRawBody() in Phalcon.
The main difference is that POST vars format allows you to send key=value pairs of data. When it comes to more complex structures (arrays, associative arrays, nested objects and so on), you will start to have problems which you will have to solve some way. It won't happen if you send JSON objects in POST/PUT request bodies. And, of course, you get serializing and deserializing OOTB in both AngularJS and Phalcon.
You should strongly consider key=value params for GET parameters only and JSON data for everything else. Obviously, you can mix those two (I mean i.e. sending new content for your article as PUT request with JSON body, but specifying article id in URL like /article?id=123).
You may be also istresed in reading REST API: Request body as JSON or plain POST data?.

Categories

Resources