django self,pk for success function after save() - javascript

I may be going about this backwards but I'm trying to use a pk in a success function to create a href to load.
The pk will be new and have been created by the save()
what I want to know is how to post the self.pk pack to the js to use it.
The javascript
JS
$.ajax({
type: "POST",
url: "/api/add/res/",
data: JSON.stringify(data),
success: function(response) {
var successMessage = $('<div>').text('New Personnel file created in database...').css({'color':'green', 'padding':'5px'}).addClass('pull-right');
$('.form-group').removeClass('has-error')
$('#submitresource').html('Added!').addClass('btn-success')
$('.modal-row' ).append(successMessage);
$.get('newres_pk'),
window.setTimeout(function(){window.location.href ="'/Personnel/results.html?id="+newres_pk+"'"},3000)
},
contentType: "application/json",
dataType: "json"
})
def set(request):
data = json.loads(request.body)
res = Resource.objects.create(
title=data['title'],
preferred_name=data['preferred_name'],
last_name=data['last_name'],
employstatus=data['employstatus'],
employer=Employer.objects.get(employer_name=data['employer']),
role=Role.objects.get(role_name=data['role']),
location=Location.objects.get(name=data['location']),
workphone=data['workphone'],
mobile_phone=data['mobile_phone'],
email=data['email'],
notes=data['notes'],
updated_by=data['updated_by'],
)
res.save()
newres_pk = res.pk
print res
return HttpResponse('"Submitted"', content_type='application/json')

When return you can include the data you want to send by ex:
from django.http import JsonResponse
data = {'message':'your message'}
return JsonResponse(data)
and in the javascript ..
success: function(response) {
console.log(response.message);

Related

Cant browse through Dictionary in Javascript

I am using Ajax to send data and as a success, it sends some data back.
$.ajax({
method: "POST",
url: "{% url 'upload-prop-images' %}",
processData: false,
contentType: false,
mimeType: "multipart/form-data",
data: fileData,
success: function (data) {
console.log(data);
console.log(data.newCard);
console.log(data.newCard.prop_name);
}
}
})
views.py :
def uploadPropImages(request):
prop_obj = list(Property.objects.filter(user=request.user).values())
new_card = {}
for obj in prop_obj:
if obj['prop_name'] == prop_name:
new_card['prop_name'] = obj['prop_name']
new_card['prop_address'] = obj['prop_address']
new_card['prop_type'] = obj['prop_type']
new_card['prop_images'] = '/media/' + obj['prop_images']
return JsonResponse({'status': 'Done', 'newCard': new_card})
In the first code block where success: function(data) {}, console.log(data) prints the data I am sending, that is {'status': 'Done', 'newCard': new_card}, but when I print, console.log(data.status) or console.log(data.newCard), I get undefined value. I cant understand why it prints undefined because I used AJAX may times earlier and It seem to work. It is how we can browser through the value of a dictionary in JAVASCRIPT, which in PYTHON is print(data['status']). Is the error anything related to the keys defined inside the AJAX function: processData, mimeType, contentType?
you need to call this
$.parseJSON();
Like this
success: function (response) {
var data= $.parseJSON(response);
console.log(data);
console.log(data.newCard);
console.log(data.newCard.prop_name);
}

cannot send json data from html to php

I cannot send JSON Data from HTML to PHP with jquery and always show fail status at console.log. Please check my code.
jsonObjects.domain = client_domain;
jsonObjects.pkg = client_package;
jsonObjects.company_name = client_company;
jsonObjects.company_email = client_email;
jsonObjects.personal_name = psn_name;
jsonObjects.personal_phone = psn_phone;
jsonObjects.personal_email = psn_email;
var JsonPush = new Array();
JsonPush.push(jsonObjects);
var JsonArray = JSON.stringify(JsonPush);
$.ajax({
type: "POST",
url: 'order.php',
data: JsonArray,
dataType: 'json',
})
.done(function (data) {
console.log('done');
console.log(data);
}).
fail(function (data) {
console.log('fail');
console.log(data);
});
Order.php file
<?php
$decoded = json_decode($_POST['data']);
var_dump($decoded);
?>
You don't need to stringify first, just post it in a keyed object and access via the key like this
let postData = { object: jsonObjects };
$.ajax({
type: "POST",
url: 'order.php',
data: postData,
dataType: 'json',
})
Then in php:
$jsonObjects = $_POST['object'];
note: you don't access the posted variable by the name of the object itself but rather the keys inside the posted object
You have no data parameter in your AJAX call. It should be:
data: { data: JsonArray },
But there really isn't any need to use JSON at all. You can just given an object as the data: option, and its properties will become POST parameters.
data: jsonObjects,
Then in PHP you can access $_POST['domain'], $_POST['pkg'], etc.

Retrieve POST JSON response

I'm writing my first Ajax request, on a Groovy/Grails platform.
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
data: {source:"${source}"},
success: function (response) {
jsonData = response;
var res = JSON.parse(jsonData);
alert(res);//
}
});
Here is the response of my controller "url"
def result = [ value: 'ok' ]
render result as JSON
But it does not work and i get an error message in my browser
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var res = JSON.parse(jsonData);
I don't understand , the response seems to be a nice formatted JSON ?
EDIT i did a print as Paul suggests :
If i execute
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response)
console.log(response.value)
jsonData = response;
}
});
The first print is :
Object { value="ok"}
The second print is
ok
If i want to get the result, how is the proper way ?
Do i have to assign the value inside the statement "success: function (response) { "
doing something like
var result
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
result = response.value
}
});
console.log("result : "+result);
This code works for me !!
Or perhaps there is a way to get the result, doing something like
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
}
});
var result = newDataB.response.somethingblablabla
or
var result = OneFunction(newDataB.response)
??????
You can make object stringified before passing it to parse function by simply using JSON.stringify().
var newDataB = $.ajax({
method: 'post',
url: "${createLink(controller: 'util',action: 'test')}",
async: false,
data: {source: "abc"},
success: function (response) {
jsonData = response;
var res = JSON.parse(JSON.stringify(jsonData));
console.log(res);//
}
});
Hopefully this may help.
You shouldn't need to parse it, if your server is providing json.
You can use dataType though to force jQuery to use a particular type:
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response);
}
});

Ajax call return list from python flask approute

I am using ajax call to post some data and now i need to return a python list from approute back to html. how i can do this. here is my code
$('#stop').submit(function(){
id = id
var services = $('#service').val()
var extra = document.getElementById('More').value
$.ajax({
type: 'post',
url: "/stopservice/"+id,
cache:false,
async:true,
data: {service: JSON.stringify(services),
extra: JSON.stringify(extra),
},
success: function(data) {
alert(data)
},
error: function(data)
{ $.unblockUI();
alert(data)
}
});
return false
});
});
and here is my approute.
listofdata = finallist
return listofdata
So basically listof data is a python list..this the the return value from approute. But i am not able to get this data in ajax.,any help
You'll need to use Flask's jsonify function (or convert the list to JSON yourself using json.dumps and send it back as application/json).
# In your route handler
return jsonify(list_of_data=list_of_data)
// In your JavaScript
success: function(data) {
console.log(data.list_of_data);
}

pass a object list view to controller with Ajax function in Javascript

I have a list object. I want to pass my list view to controller with Ajax function My code like :
function Save()
{
debugger;
if(!ValidateInput()) return;
var oRecipe=RefreshObject();
var oRecipeDetails=$('#tblRecipeDetail').datagrid('getRows');
var postData = $.toJSON(oRecipe);
var mydetailobj= $.toJSON(oRecipeDetails);
// postData="Hello world!!!!!!! Faruk";
//return;
$.ajax({
type: "GET",
dataType: "json",
url: '/Recipe/Save',
data: { myjsondata : postData, jsondetailobject : mydetailobj},
contentType: "application/json; charset=utf-8",
success: function (data) {
debugger;
oRecipe = jQuery.parseJSON(data);
if (oRecipe.ErrorMessage == '' || oRecipe.ErrorMessage == null) {
alert("Data Saved sucessfully");
window.returnValue = oRecipe;
window.close();
}
else {
alert(oRecipe.ErrorMessage);
}
},
error: function (xhr, status, error) {
alert(error);
}
});
}
Normally my code run successfully if my list length <=3/4 but when my list length >4 here a problem arise. I could not find out what is bug? please any one suggest me
Note : Here i try to pass by list object convert to JSON data
Why type "GET"? It is obvious that you want to post your data back to the controller. Change it to "POST" and try.
$.ajax({
type: "POST",
dataType: "json",
...

Categories