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);
}
Related
I'm building a program that searches documents in ASP.NET Core. I'm passing the search data from a text box to the controller through an Ajax request but the controller isn't receiving the string.
I've tried changing how the ajaxData field is defined, adding quotations around 'search' and even turning the whole thing into a string but I can't get it to pass to the controller.
This is the code for the request:
ajaxData = {search: $("#textSearchBox").val()}
console.log(ajaxData);
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: ajaxData,
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
And this is the top of the Controller's GetDocuments function:
[Route("GetDocuments")]
public async Task<IActionResult> GetDocuments(string search)
{
No error messages anywhere. The Console shows an Object that contains 'search: "Test"' but when I hit the breakpoint in GetDocuments 'search' is null.
I think is more elegant way to use GET in this case then you should change your code to
var ajaxData = $("#textSearchBox").val();
url: "#Url.Action("GetDocuments", "DocumentSearchApi")"?search=ajaxData
and remove data: ajaxData
Because you want to get something from the search. Using the post is when you want to modify the data from API
you need use JSON.stringify() when sending data to a web server, the data has to be a string not a object
$.ajax({
type: 'POST',
url: "#Url.Action("GetDocuments", "DocumentSearchApi")",
data: JSON.stringify(ajaxData),
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function (e) {
//Error Function
},
success: function (jsonData) {
//Success Function
},
fail: function (data) {
//Fail Function
}
});
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);
}
});
I'm trying to get the extract of a random Wikipedia page using Ajax. I've got as far as getting the data, but I'm having trouble outputting it.
Here's my code:
$.ajax({
type: "GET",
url: "https://simple.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&exsentences=10&format=json&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data) {
console.log(data);
var text = data.parse;
document.getElementById('div_text').innerHTML = text;
},
error: function (errorMessage) {
}
});
The console logs the data fine, but the output in the browser is simply undefined.
Clearly, the problem is this line:
var text = data.parse;
Where am I going wrong?
The data is not in data.parse but in data.query.pages and in there the first object.
So change you success method to
success: function (data) {
var pages = data.query.pages;
var text = pages[ Object.keys(pages)[0] ].extract;
document.getElementById('div_text').innerHTML = text;
}
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);
If I need to call a controller like this:
name.php?data={"user":"test","pass":"test"}
In order to obtain the information I need, via .ajax, I need help setting the variable to be sent with that specific format.
I used to the following code:
var arr = [{
data: {
"user" : $("#usuario").val(),
"pass" : $("#password").val()
}];
arr = JSON.stringify(arr);
However if doesn't send the right output, I've been said I need to send the variable with the json on it.
function callAjax(url, arr) {
var response = null;
jQuery.ajax({
url: url,
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(data) {
response = data;
},
error: function(jqXHR, textStatus, errorThrown) {
response = errorThrown;
},
timeout: 5000
});
return response;
}
Any advises?
Best Regards!
This link will help you a lot!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I used .post instead and solved the issue