How can I convert the output of drp.getDateRange to an array so that I can post it via AJAX?
I have updated this code to represent the advice given below
<script>
var drp;
var myArray = [];
function makedatepicker() {
drp = $("#myDate").datepicker({});
}
function getRange() {
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
data: data,
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
}
});
}
$(document).ready(function () {
makedatepicker();
});
</script>
Update
Note on JSON. The default encoding will be url form encoded. If you want the request to send the data as JSON, you will need to add..
content-type: "application/json; charset=utf-8",
also if you are returning JSON, you should add ...
datatype : "json",
Not sure which scripting language your using on the back end, but if PHP, you can send back array data like this
echo json_encode($myArray);
I will add the JSON stuff to the sample code below.
End Update
If you use .serialize() you an send it as ajax data and it will show up in your post or get array.
If you are working with an array, you might want to use .serializeArray()
You can view an object or array in your developer tools (F12 in Chrome or FF), by using console.dir(someObject);
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
beforeSend : function (){
console.log("Before Send: Data looks like..");
console.dir(data);
},
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
console.log("parsing JSON ...");
console.dir($.parseJSON(response));
}
});
Chrome Developer Tools Console, this is where you will see anything that you console.log or console.dir
You can check the JSON that is being sent by clicking the Network tab. Then click the name of the ajax script and it will show you the data being sent. (Also, clicking on the "response" tab will show you what is being sent back by your script.)
In the example below I am sending an ajax request using the above code and it is showing that the data is indeed a JSON object.
Related
I have an array of objects that needs to be submitted to Django view.
I stringify it and checked result in console log. Up to this point it works. However, when I try to retrieve it in my view I get some errors.
I tried to edit my code similarly to what I've found on the topic, unfortunately nothing helped.
I tried ast.literal_eval instead of json.loads, passing 'items[]' and collecting data via request.POST.getlist as well as solution with request.body and request.is_ajax(). Yet, neither allowed me to retrieve the data.
var items = [];
var formInput = $('#inputbox').val();
items.push({'item': formInput , 'metrics': metrics.toString()});
$('#id_search').click(function( event ) {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '{% url "list_of_items" %}',
data: {'items': JSON.stringify(items),},
success: function (response) {
console.log(data);
}
});
event.preventDefault();
});
and in views.py:
def list_of_items(request):
data = request.POST.get('items')
data_received = json.loads(data)
#another approach:
response_json = request.body
struct = {}
try:
response_json = response_json.decode('utf-8').replace('\0', '')
struct = json.loads(response_json)
except:
print('bad json: ', response_json)
#(...)
I looks like an empty object is passed.
TypeError at /list_of_items
the JSON object must be str, not 'NoneType'
This view receives another POST request from the JS form within same template (list_of_items.html) and I wonder if it's interfering with my ajax POST.
You are not sending the data correctly. From the docs:
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data.
You need to send the data as key:value pair or you need to decode the request.body as
data = request.body.decode('utf-8')
data_received = json.loads(data)
This is the correct way to send ajax request.
$.ajax({
type: 'POST',
url: '{% url "list_of_items" %}',
data: {'items': JSON.stringify(items),},
success: function (response) {
console.log(data);
}
});
I also think that you have bound the submit event and click event incorrectly. Also you are sending ajax request on submit event without preventDefault
I try to send list of object like [{"name":"Vasya"},{"name":"Lila"}]
It's my code:
$.ajax({
url: url
, type: 'POST'
, contentType: 'application/json'
, data: data
, success: function(response) {
showPopup(response.successMessage);
}
});
Where alert(JSON.stringify(data)); shows: [{"name":"Vasya"},{"name":"Lila"}]
But when I am checking my request in chrome debug mode the request contains undefined= instead correct data.
What I do wrong? Is this syntax incorrect according to JSON?
You need to stringify the object when sending it so that you send JSON.
, data: JSON.stringify(data)
A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.
I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.