I am trying to get a JSon from my server. I am calling the API like this:
Ext.data.JsonP.request({
url: 'http://dev.mysite.com/temp.cfm',
callbackKey: 'callback',
timeout: 40000,
params: {
format: 'json'
},
success: function(result, request) {
// Get the weather data from the json object result
var weather = result; console.log('Succ');
},
failure: function(result, request) {
// Get the weather data from the json object result
var weather = result; console.log('Fail');
},
callback: function(result, request) {
// Get the weather data from the json object result
var weather = result; console.log('CallB');
}
});
I am using Coldfusion as Serverside. So, I am simply doing this:
<cfreturn '#url.callback#({\"LOGINSTATUS\":\"fail\"})'>
That returns the following string:
Ext.data.JsonP.callback1({\"LOGINSTATUS\":\"fail\"})
But my request always times out.
I couldn't figure out what was the actual problem. I just tried using cfm file instead of cfc on server side and everything started working.
If anyone could explain why this happened I'll accept that explanation as correct answer.
Thanks DmitryB and Sharondio for you time and trying to help me fix it. I really appreciate your help.
Related
I am trying to extract the sys_id value and store it as a variable within postman. Currently I am not getting any errors using the following
var data = JSON.parse(responseBody);
pm.environment.set('sys_id', pm.response.json().sys_id);
It is saving the variable, but showing null within the value
Response Body
{
"result": {
"sys_id": "5ae690c11ba421d46557a9b7bd4bcbbf",
}}
Any help will be appreciated!
Without knowing the whole value of the response body - and based on this link, you can try this code - which I tested with another JSON data payload:
Code:
let data = pm.response.json();
pm.environment.set('sys_id', data.result.sys_id);
console.log(pm.variables.get("sys_id"));
Managed to resolve it with the following code:
var responseData = JSON.parse(responseBody);
postman.setEnvironmentVariable("sys_id", responseData.result.sys_id);
I require help to execute a postman test which requires a response output from another test. I have checked with various forums but a solution is not available for this particular scenario.
Example
Test 1 response:
{
"items": [
{
"email": "archer+qa01#gmail.com",
"DocumentName": "tc",
"type": "URL",
"url": "https://localhost:8443/user/terms?statusno=a5f2-eq2wd3ee45rrr"
}
]
}
Test 2:
I need to use only the a5f2-eq2wd3ee45rrr part of the response data from Test 1, this can be seen in the url value above. I need to use this value within Test 2
How can I make this work with Postman?
Not completely sure what the response data format is from the question but if it's a simple object with just the url property, you could use something simple like this:
var str = pm.response.json().url
pm.environment.set('value', str.split('=', 2)[1])
This will then set the value you need to a variable, for you to use in the next request using with the {{value}} syntax in a POST request body or by using pm.environment.get('value') in one of the test scripts.
Edit:
If the url property is in an array, you could loop through these and extract the value that way. This would set the variable but if you have more than 1 url property in the array it would set the last one it found.
_.each(pm.response.json(), (arrItem) => {
pm.environment.set('value', arrItem[0].url.split('=', 2)[1])
})
If you get JSON response and then send JSON in body, I would do the following:
1) In test script(javascript):
var JsonBody = pm.response.json();
var strToParse = JsonBody.url;
var value = strToParse.slice(indexOf("?status=")+"?status=".length);//parse string
//manually but you can google for a better solutions.
pm.environment.get("varName" , value)
2) You can use it! In scripts like: pm.environment.get("varName"), and everywhere else using {{varName}}
I am trying to use ember-data to get a simple registration form to save on my server. The call technically works, but the success callback is never trigger on the promise, and I have no idea why.
The server receives the data from the front end and successfully saves it to the database. It then returns status code 201 for CREATED. I can see the successful response happening in the Chrome debugger. But even when the server responds with a successful status, the error callback is triggered on the save's promise. I've confirmed this happens every time by putting a debugger; statement in the error callback.
My router's model is hooked up like this:
model: function() {
return this.store.createRecord('registerUser');
}
And I have a simple register function in my controller:
register: function() {
var self = this;
this.get('model').save().then(function() {
self.transitionToRoute('index');
}, function(resp) {
if (resp.responseJSON) {
self.get('model').set('errors', resp.responseJSON.errors);
}
});
}
Every time my server comes back with a response, success or failure, the failure callback is hit. If I have errors in the response (for invalid data or something), the errors are successfully displayed in the form. I can see the request coming in properly, and the data is stored in the database. So, the save is technically successful, but ember doesn't seem to know that it is even though a successful 201 status is returned from the server (which can be verified in the Chrome debugger).
The only thing I can think of is that ember-data's adapter is doing something that I'm not aware of, but I am just using the default RESTAdapter and haven't touched it. Is there anything else
If it makes a difference, the server is running Play 1.2.5. I don't know if that makes a difference in the response's header or something like that.
Any help would be greatly appreciated. Thank you for your time!
Mike
SOLUTION
So, the issue was to do with the JSON response. The two problems:
I did not include an ID in the response
I did not "wrap" the response in a "registerUser". This is necessary to match the model name.
Below is a valid response:
{
"registerUser": {
"id": 11,
"email": "mike999#test.com",
"password": "12345",
"password2": "12345",
"name": "Mike"
}
}
Ember Data is expecting the model in the response, so sending back a success http status doesn't mean it will hit the success endpoint. When it tries to serialize your response (or lack of response) it's probably failing which would be why it's hitting the failure function. A big reason for the response is the id of the record.
The model returned should be in the following format
{
registerUser:{
id: "123",
attr: "asdf"
}
}
https://github.com/emberjs/data/blob/master/TRANSITION.md
Happy coding weekend to everyone!!!.
I'm stuck trying to send a JSON object via $.load() of jQuery, i want to send it with the GET method, this is the code that i have in my javascript code, I attached the Ajax request that receives the JSON Object for clarity:
function ajaxLoadClasses() {
$.ajax({
url: 'load_classes/',
type: 'GET',
dataType: 'json',
success: function(json) {
$.each(json, function(iterator,item) {
loadViaGet(item);
});
},
error: function(xhr, status) {
alert('Sorry, there was a problem!');
},
complete: function(xhr, status) {},
});
}
function loadViaGet(item) {
$div = $('div.myClass');
//Here is where I'm stuck, I'm not sure if this is the way to send the JSON obj
$div.load('thisAppURL/?json=' + encodeURIComponent(item), function() {
alert('Load was performed');
});
}
The "item" json obj received was made out of a Model of Django using
jsonToSendToAjax = serializers.serialize('json', obj)
And I don't think that I'm using the correct methods in my Django to deserialize the JSON object or to convert the JSON object into a Python object so I can handle it in my view and send it to a template:
def popUpForm(request):
jsonData = request.GET['json']
deser = serializers.deserialize('json', jsonData)
#This could be another way to convert the JSON object to a Python Object
#pythonObj = simplejson.loads(jsonData)
return render_to_response('class_pop_up_form.html', deser)
It will be very helpful if someone can help me with this!! I'm really struggling with it but I don't find the right way to do it.
EDIT 1 :
I want to send the JSON object via the GET with the $.load() function, not with the POST method,as I read in the jQuery api: http://api.jquery.com/load/ the $.load() method works as follow: .load( url, [data], [complete(responseText, textStatus, XMLHttpRequest)] )
The POST method is used if data is provided as an object; otherwise, GET is assumed.
EDIT 2:
Forget about sending the json object via the GET method, now I'm using the POST method, but now I don't figure out how to use that json object in my Django View.py, don't know if i need to deserialize it or not, the format of the json object that I'm using is the following:
{"pk": 1,
"model": "skedified.class",
"fields": {
"hr_three": null,
"group": 1,
"name": "Abastecimiento de agua",
"day_three": null,
"day_one": "1 , 3",
"hr_one": "10+/3",
"online_class": null,
"teacher_name": "Enrique C\\u00e1zares Rivera / ",
"day_two": null,
"class_key": "CV3009",
"hr_two": null }
}
This isn't how jQuery suggests you should send the data and it's probably not a good idea to do it this way either. Your url gets very ugly and long very quick if you add the json string to it like that.
Use the second argument for $.load; "data" (see http://api.jquery.com/load/) instead. So something like
$div.load('thisAppURL', {"json": encodeURIComponent(item)});
Also, if you want to trace the output, I'd sugest using the third argument, the callback function, and use console instead of alert. You can get the actual return from the server that way too. So you'd get something like:
$div.load(
'thisAppURL',
{"json": encodeURIComponent(item)},
function(response, status, xhr){
console.log(response);
}
);
the question was not clear to me but you can send json via load as the second argument
$div = $('div.myClass');
//Here is where I'm stuck, I'm not sure if this is the way to send the JSON obj
$div.load('thisAppURL/?json=' + encodeURIComponent(item),{"name":"john","age":"20"}, function() {
alert('Load was performed');
});
for converting javascript array to json see this answer Convert array to JSON
and for deserializing json in django Django Deserialization
I'm a complete Flex noob, so I apologize in advance if I'm missing something obvious.
I wrote a fairly simple file uploader in Flex, which calls my Django back-end via URLRequest (the FileReference object handles the upload). My upload works as intended and I have Django return a HTTPResponse object. As such, I'd like to read the contents of the HTTPResponse object.
Any thoughts?
something along the lines of
<mx:HTTPService id="myHTTPRequest"
url="{whatever your url request is}"
result="resultHandler(event)"
fault="faultHandler(event)"
showBusyCursor="true"
resultFormat="object">
then inside the resultHandler something like this
private function resultHandler (event : ResultEvent) : void {
var obj : Object = event.result;
//do something with returned object
}
Debug at the point of the resultHandler to see exaclty whats being returned, make sure its what you think should be getting returned.
By the time it gets to the client it's just a normal HTTP response so treat it like any other response
I am also new to flex and I ran in the same problem when doing an upload to a Java Rest backend, I solved it using the DateEvent on the FileReference. To get the response data use something like this.:
var fileRef:FileReference = new FileReference();
fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, responseHandler);
var request:URLRequest = new URLRequest("yourUrl");
fileRef.upload(request, "fileData");
private function responseHandler(event:DataEvent):void {
var response:XML = new XML(event.data);
//Note the DataEvent: this is the event that holds the response.
//I sent back data as xml
}
Your response should always be a successful HTTP status code (200), if your backend sends status 500 codes it will not trigger the DateEvent. Server errors can still be caught with a HTTPStatusEvent, but then you don't have access to the response.
you can access the response like so in your onComplete event handler:
private function saveCompleteHandler(event:Event):void {
var loader:URLLoader = event.currentTarget as URLLoader;
trace("saveCompleteHandler - event returned:" + loader.data as String);
}
we do this this to get json fron a java web service.
you just need to use a URLLoader to load the URLRequest in the first place:
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, statusHandler, 10000);
loader.addEventListener(IOErrorEvent.IO_ERROR, saveErrorHandler, 10000);
loader.addEventListener(Event.COMPLETE, saveCompleteHandler, 10000);
var request:URLRequest = new URLRequest("http:/whereverer");
request.method = URLRequestMethod.GET;
loader.load(request);