Pass objects in ajax request - javascript

I need to pass objects in ajax request in order to "PUT" files or data to my rest service. How can i do it? Thank you.
update
i have this code:
var invoice = {};
invoice.POSWorkstationID = "POS7";
invoice.POSClerkID = "admin";
invoice.CustomerName = "Alice in Wonderland Tours";
invoice.IsFreightOverwrite = true;
should i do this:
parameter = "{BillToCode:"+invoice.CustomerName+",POSWorkstationID:"+invoice.POSWorkstationID+",POSClerkID:"+invoice.POSClerkID+",IsFreightOverwrite:"+invoice.IsFrieghtOverwrite+"}";
and this:
data: JSON.stringify(parameter),

Normally, you can use jquery to do this may be like this:
$.ajax(
{
type: "PUT",
dataType: "json",
data:POSTData,
url: 'www.youurlhere.com/path',
complete: function(xhr, statusText)
{
switch(xhr.status)
{
//here handle the response
}
}
});
POSTData is the data in json format that u supply to the rest, you can turn an object into a json format by simply pushing the attributes but respecting JSON Format syntax

Take a look at jQuery post http://api.jquery.com/jQuery.post/
you have few options there:
$.post("test.php", $("#testform").serialize());
$.post("test.php", { name: "John", time: "2pm" } );

The best way to communicate client and server side is (IMHO) JSON.
You could serialize your object into json format, with this lightweight library =>
http://www.json.org/js.html
Look for stringify method.

Related

Problem sending information between Django template and views using AJAX call

I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page.
With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix.
This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert.
var arr = { City: 'Moscow', Age: 25 };
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = norm_data.toString();
alert( norm_data );
}
});
This is my Django URLs code to receive the request:
path('applications/1/normalize', views.normalize, name="normalize")
This is the python view to retrieve the code and send it back to the javascript file:
from django.http import JsonResponse
def normalize(request,*argv,**kwargs):
norm_data = request.POST.get(*argv, 'true')
return JsonResponse(norm_data, safe = False)
You need to parse your Object to an actual json string. The .toString() will only print out the implementation of an objects toString() method, which is its string representation. By default an object does not print out its json format by just calling toString(). You might be looking for JSON.stringify(obj)
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = JSON.stringify(norm_data);
alert( norm_data );
}});
I've observed that there's a difference between POST data being sent by a form and POST data being sent by this AJAX request. The data being sent through a form would be form-encoded whereas you are sending raw JSON data. Using request.body would solve the issue
from django.http import JsonResponse
def normalize(request):
data = request.body.decode('utf-8')
#data now is a string with all the the JSON data.
#data is like this now "arr%5BCity%5D=Moscow&arr%5BAge%5D=25"
data = data.split("&")
data = {item.split("%5D")[0].split("%5B")[1] : item.split("=")[1] for item in data}
#data is like this now "{'City': 'Moscow', 'Age': '25'}"
return JsonResponse(data, safe= False)

How to get Google maps URL with a 'placeid' with AJAX?

I have a URL which I can open on browser and view the JSON data. The URL looks something like this:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE
Now when I try to access this with jQuery AJAX, I fail to get any results, instead I get an error.
My AJAX call looks some like this:
$.ajax({
url: https://maps.googleapis.com/maps/api/place/details/json,
data: {
'placeid': 'ChIJZeH1eyl344kRA3v52Jl3kHo',
'key': 'API_KEY_HERE'
},
dataType: 'json',
success: function(response) {
alert(JSON.stringify(response));
},
error: function(error) {
alert(JSON.stringify(error));
}
});
var API_KEY = api_key;
var placeid = placeid;
var API_URL = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${placeid}&key=${API_KEY}`
$.getJSON(API_URL, {
tags: placeid,
tagmode: "any",
format: "json"
},
function(data) {
alert(data);
});
If I build it up correctly, this should be the way to send the data correctly to the api, using the placeid inside the url string together with the api_key.
Then you use a getJSON instead of json because I assume you want to get the place data? Assuming to what you're doing in the ajax you made.
Maybe explain further what you mean with how to get google maps url with place id? Hope it helps you out :)

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

Fetching JSON data from a URL in javascript?

I am trying to retrieve data from a URL of the form http://www.xyz.com/abc.json.
I have been trying to achieve this using the $.ajax method in the following manner.
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "http://www.xyz.com/abc.json.",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
However I am being unable to get this to run. I need to loop through the retrieved data and check for some specific conditions. This could have been achieved easily with the $.getJSon if the json data had a name to it, however the file is of the form:
[{
"name": "abc",
"ID": 46
}]
because of which I have to effectively convert and store it in a Javascript object variable before I can use it. Any suggestions on where I might be going wrong?
It looks like you will want to convert that data response to a json object by wrapping it with { } and then passing that to the json parser.
function (data) {
json = JSON.parse("{\"arr\":"+data+"}").arr;
}
Then to get your data, it would be
json[0].name //"abc"
So your question is how to convert a string to Json object?
If you are using Jquery you can do:
jQuery.parseJSON( jsonString );
So your return should be:
return jQuery.parseJSON( json );
You can read documentation here

Sending a multi-level javascript object to the server with AJAX fails

I have a javascript object that looks somthing like this:
var obj = {
"name": "username",
"userid": "9999",
"object1": {
"subObject1": {
"subArray1": [],
"subArray2": []
},
"subObject2": {
"subArray3": [],
"subArray4": []
}
},
"object2": {
"subObject3": {
"subArray5": [],
"subArray6": []
}
},
"array1": [],
"array2": []
};
I have tried to use a jQuery ajax call like this:
$.ajax({
url: "test.php",
type: "POST",
dataType: "text",
processData: false,
data: obj,
success: function(data, status) {
alert("Sucsess");
}
});
The problem is that PHP doesn't receive anything. The $_POST variable is empty. I'm not sure what I'm doing wrong.
Thanks
First, include JSON2.js (Link at bottom of that page) on the page, then change your call to this:
$.post(
"test.php",
data: JSON.stringify( obj ),
function(data, status) {
alert("Sucsess");
});
Try out jQuery 1.4.1 the $.param function was completely rewritten to support things like this.
Why not send it by using something like the json2 library to serialize the whole object as JSON, then send that via a single parameter? I don't know PHP but I would be stunned if there weren't dozens of alternative JSON parsers available.
I don't believe it is possible to send a data object like that.
If you wanted to do something like that you would have to serialize it before you send the data and then unserialize at the server. HTTP has it's limits.

Categories

Resources