Send Json via $.load() of jQuery in a GET request to Django - django

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

Related

Telegram bot sendMediaGroup() in Postman - JSON-serialized array?

I'm using Postman app to interact with a Telegram bot api. I've sent photos using the sendPhoto() method, like this:
https://api.telegram.org/botToken/sendPhoto?chat_id=00000000&photo=AgAC***rgehrehrhrn
But I don't understand the sendMediaGroup() method. Can someone post an example how to compose the https string to send two photos?
Thanks
You need to send a POST request at the url https://api.telegram.org/botToken/sendPhoto with a JSON body. You are using the url to specify all the parameters of the request but urls are only 2000 characters long. The body of a POST request, instead, has no limits in terms of size. The JSON body should look something like this:
{
"chat_id": 777000,
"media": [
{
"type": "photo",
"media": "https://example.com/first_photo_url.png",
"caption": "an optional description of the first photo",
"parse_mode": "optional (you can delete this parameter) the parse mode of the caption"
},
{
"type": "photo",
"media": "https://example.com/fsecond_photo_url.png",
"caption": "an optional description of the second photo",
"parse_mode": "optional (you can delete this parameter) the parse mode of the caption"
}
],
}
For more info see:
how to send JSON (raw) data with Postman
and
sendMediaGroup Telegram API's method.
You must send JSON as a string, or serialized JSON, to Telegram API. The format is as same as #GioIacca9's answer.
Note: only the caption in the first image will be showen.
Have a try this Python code.
def send_photos(api_key, chat_id, photo_paths):
params = {
'chat_id': chat_id,
'media': [],
}
for path in photo_paths:
params['media'].append({'type': 'photo', 'media': path})
params['media'] = json.dumps(params['media'])
url = f'https://api.telegram.org/bot{api_key}/sendMediaGroup'
return requests.post(url, data=params)
if __name__ == '__main__':
send_photos('your_key', '#yourchannel', ['http://your.image.one', 'http://your.image.two'])

Validate response in Postman test script

I am inserting data in postman. I want to apply validation from post method in test script. I am new to postman, I am not able to understand.
Here is the JSON.
{
"firstname": "pradeep",
"lastname": "tiwari",
"mobile_no": 9911844349,
"email": "pradeep#gmail.com",
"user_type": 4,
"password": "pradeep1",
"confirmPassword":"pradeep1",
"dob":"nanana",
"u_org":25,
"isfoundingpartner":"undifine",
"gender":1
}
You can use built in snippets for starters to validate your basic response messages. https://learning.getpostman.com/docs/postman/scripts/test_examples/
In order to carry out validation on your responses, you will first need to parse the data into a JavaScript object using below
var jsonData = pm.response.json();
You can use the below code to check for particular values in the response body
pm.test("Verify Json values", function () {
pm.expect(jsonData.firstname).is.to.equal("pradeep");
pm.expect(jsonData.lastname).is.to.equal("tiwari");
pm.expect(jsonData.gender).is.to.equal(1); `
});

Postman - Use part of the response data from one test in another test

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}}

Ext.data.jSonP Sencha API with Coldfusion

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.

Why do I get an empty data response?

I've gotten the built in read action to work in the past but now it is not working. I also created a custom action which will not work.
When I try to post the action to this url:
https://graph.facebook.com/me/teamtutorials:complete?access_token=AAACOYImsskcBAGlF33o6awIqxmQ078BVdHUY72CF7GUqTHUhEcpKLdH8ZCKeyQbBqBDlnHwUMwt5aLOzpBmiWQqpvWsNAeHDMPSo2OQZDZD&tutorial=http://teamtutorials.com/web-development-tutorials/why-zen-coding-is-an-awesome-time-saver?
all I get in response is:
{
"data": [
],
"paging": {
"next": "https://graph.facebook.com/me/teamtutorials:complete?access_token=AAACOYImsskcBAGlF33o6awIqxmQ078BVdHUY72CF7GUqTHUhEcpKLdH8ZCKeyQbBqBDlnHwUMwt5aLOzpBmiWQqpvWsNAeHDMPSo2OQZDZD&tutorial=http\u00253A\u00252F\u00252Fteamtutorials.com\u00252Fweb-development-tutorials\u00252Fwhy-zen-coding-is-an-awesome-time-saver\u00253F&offset=25&limit=25"
}
}
What causes this type of response?
That looks like the response you'd get to a HTTP GET request; you need to make a HTTP POST request to create a new action
if your code/proxy can't make POST request outbound or you can fake it by making a GET request and including an extra parameter &method=post