Access ajax elements with django - javascript

i am using ajax to fetch django model and get results
views.py
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data':data,})
ajax request
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
if (data) {
console.log(data.title);
}
}
});
and i am getting this response from django
{"data": "[{\"model\": \"app.company\", \"pk\": 1, \"fields\": {\"title\": \"Facebook\"}}, {\"model\": \"app.company\", \"pk\": 2, \"fields\": {\"title\": \"Fabook\"}}]"}
my question is how i can access the title.

You here double serialized the value for the "data" key: first by the serializers.serialize(..) that constructed a string, and the you again serialize it (constructing an string literal), making it harder to obtain the elements.
We can prevent this, for examply by turning the JSON blob back into a vanilla Python object first:
from json import loads as json_loads
def browse_jobs(request):
keyword = request.GET.get('keyword', None)
company = Company.objects.filter(title__icontains=keyword)
data = serializers.serialize("json", company, fields=('title'))
return JsonResponse({'data': json_loads(data), })
Then the AJAX call will receive a JSON blob where "data" does not map to a string, but a list of subdictionaries, making it easier accessible.
Here there are two results for your query, you can print the first title with:
$.ajax({
url: '/browse_jobs',
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
console.log(data.data[0].fields.title);
}
});

Related

Parse return value from $ajax call in JavaScript from MVC Controller

I'm using VS2022 with C# and I'm trying to use an $ajax get method in my JavaScript function. I'm sending a parameter and returning a string[] list but when I receive the return I use JSON.stringify but when I try to use JSON.Parse it fails. The Javascript code is
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
}).done(function(result) {
let userObj = JSON.stringify(result);
let resultList = JSON.parse(userObj);
});
The code in the controller which returns the list is simple at the moment until I get the return working
[HttpGet]
public ActionResult GetCategories(string ctgData)
{
string[] categoryList = { "Food & Drink", "Sport & Fitness", "Education", "Housework", "Fiction", "Horror Books", "Fantasy", "Magic" };
return Json(new { data = categoryList });
}
The value in result is
{"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
I've tried a number of different ways in Parse but it always fails, can you tell me what I'm missing to get my resultList to contain the string array.
You don' t need to parse anything. It is already java script object
$.ajax({
type: "GET",
url: '/Home/GetCategories/',
contentType: 'application/json',
datatype: 'json',
data: { ctgData: JSON.stringify(relvalue)}
sucess: function(result) {
let data=result.data; // data = ["Food & Drink","Sport & Fitness",..]
}
});
use this:
JSON.parse(JSON.stringify(data))
const data = {"data":["Food & Drink","Sport & Fitness","Education","Housework","Fiction","Horror Books","Fantasy","Magic"]}
const resultJSON = JSON.parse(JSON.stringify(data))
console.log("json >>>", resultJSON)

Ajax Data Call with or without slash in Codeigniter getting error

suppose my URL is example.com/controller/method/
when I use this ajax code it makes URL like example.com/controller/method/method which not getting data.
function getProductList() {
var category = document.getElementById('Category').value;
$.ajax({
type: 'POST',
url: 'GetProductList',
data: {CategoryId: category},
dataType: 'json',
cache:false,
success: function (response) {
}
});
}
but when my URL is example.com/controller/method then ajax getting data correctly. but i want to get data from the database on both situations.
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. So you can not use example.com/controller/method/method.The segments in a URI normally follow this pattern: example.com/class/function/id/ , So your last method argument treated as a id. so create method in controller with the default argument Ex. public function mymethod($method = ''){ /** Your logic goes here */ }

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)

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

JQuery $.ajax() post - data in a java servlet

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Categories

Resources