I'm having trouble with data formatting. I have several 3-D arrays (arrays of arrays of arrays for the sticklers) that I want to pass to a PHP function through an ajax POST. I've tried combining them into an object and then stringifying it with JSON.stringify:
var postFile = '/games/saveMap';
var postObj = {'mapTiles':mapArray,
'tileRots':rotations,
'ceilings':ceiling,
'floors':floor,
'pitDepth':depth,
'sections':sectionNames,
'mapName':$('#mapName').val()
}
var postData = JSON.stringify(postObj);
$.ajax({
type: 'POST',
url: postFile,
data: postObj,
success: function(data)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
Regardless of whether I send postObj or postData I get an error that the index is undefined for all of the indexes in the object. What is wrong with my format? What format does the POST need to detect my indexes?
EDIT: While I don't see a problem in the server side syntax, it is what is throwing the "undefined index" error:
$mapName=$_POST['mapName'];
$sectionNames=$_POST['sections'];
$mapArrays=$_POST['mapTiles'];
$rotations=$_POST['tileRots'];
$ceilings=$_POST['ceilings'];
$floors=$_POST['floors'];
$pitDepth=$_POST['pitDepth'];
Try this instead:
$.ajax({
type: 'POST',
url: '/games/saveMap',
data: {
'mapTiles':mapArray,
'tileRots':rotations,
'ceilings':ceiling,
'floors':floor,
'pitDepth':depth,
'sections':sectionNames,
'mapName':$('#mapName').val()
},
success: function(data)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
The problem was referencing the object on the PHP side. The correct syntax turned out to be
$mapName=$_POST->mapName;
$sectionNames=$_POST->sections;
$mapArrays=$_POST->mapTiles;
$rotations=$_POST->tileRots;
$ceilings=$_POST->ceilings;
$floors=$_POST->floors;
$pitDepth=$_POST->pitDepth;
Something I should have remembered from my Java/C++ days.
Related
I am trying to fetch the data from php file by passing dynamic query string on ajax URL section.But while I changing datatype html to json. It is popping up error
jQuery(".nks_cc_trigger_element").click(function(){
var str = jQuery(this).attr("data-product_id");
jQuery.ajax({
url: "/ajax_product.php?q="+parseInt(str),
type: 'POST',
dataType: 'json',
success: function(result){
jQuery("#nks-content-1 > div").html(result);
console.log(result);
},
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
alert(jqXHR.responseText);
}
}
}).done(function() {
});
>>PHP CODE
echo json_encode($data) ;
Use the data key/attribute and use the POST method, but don't pass the queries through the URL.
$(".nks_cc_trigger_element").click(function(){
var str = $(this).attr("data-product_id");
$.ajax({
url: "ajax_product.php",
type: 'POST',
dataType: 'json',
data: //json data,
success: function(result){
//success code
},
error: function(jqXHR, error, errorThrown) {
//error code
}
});
});
I need to make a request as follows:
var url="http://127.0.0.1:8080/simulate/";
$.ajax({
url: url,
type: 'POST',
data:{ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
},
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
But in this way, the request.POST object is not organizing the companies into a nested json array. Instead it makes it into a 2D array as follows:
<QueryDict: {u'student_num': [u'10'], u'students': [u''], u'companies[2][weight]': [u'9'], u'companies[1][weight]': [u'11'], u'company_num': [u'10'], u'companies[0][weight]': [u'10'], u'csrfmiddlewaretoken': [u'RpLfyEnZaU2o4ExxCVSJkTJ2ws6WoPrs']}>
In this way, I feel hard to reorganize the companies into a list of objects. I checked some other questions, some people say we should do this:
companies:"[{weight:10},{weight:11},{weight:9}]"
And then use json.loads to parse the string back to a list of objects. But I am keep getting parsing error if I use codes like this:
company_array = request.POST['company_array']
company_array = json.loads(company_array)
or this:
company_array = json.load(StringIO(company_array))
So what should be the correct way to handle nested JSON object?
You should use JSON.stringify() to stringify your data before sending it:
$.ajax({
url: url,
type: 'POST',
data: { data: JSON.stringify({ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
}) },
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
Then you can parse with json.loads() on the server side:
data = json.loads(request.POST.get('data'))
You might find the answers here useful: Reading multidimensional arrays from a POST request in Django
You can try look to django-SplitJSONWidget-form and get decision from it.
I have the following function:
function LogEvent(ID,description) {
var userName = document.getElementById('ctl00_ContentPlaceHolder1_username').value;
var download_link = document.getElementById('ctl00_ContentPlaceHolder1_url_download').value;
$.ajax({
type: "GET",
url: "Logger.aspx",
data: { person: userName, item: ID, desc: description },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: {
$.fileDownload(download_link);
}
});
}
Now I get an error around the $.fileDownload(download_link); line.
Uncaught SyntaxError: Unexpected token .
If I remove the entire success section it works fine, if I replace the $.file... with alert('hi'); I get a similar error.
Note, the filedownload function is the jquery.download plugin, but I know the issue is more general as noted when using alert - which also doesn't work.
I'm not sure where I am going wrong with this code?
It should be
success: function() {
$.fileDownload(download_link);
}
As it is, the parser is probably assuming
{
$.fileDownload(download_link);
}
is an object, which doesn't make sense since objects should be key-value pairs.
You've forgotten the function() part of the callback function, or you're mixing object and function notations.
success: function() {
$.fileDownload(download_link);
}
Forgive me, I am a complete JSON newbie here. I'm trying to load a file of json information from an external file, and I'm not sure how I can tell if the information has loaded or not. Here's what I have so far:
$(document).ready(function(){
$.ajax({
dataType: 'json',
success: function(string) {
data = $.parseJSON(string);
console.log(data);
alert(data);
document.write(data);
},
url: 'http://www.site.com/mystuff.php'
});
});
I've tried putting all kinds of stuff to see if the info has loaded, as you can see, and nothing has. How do I know if I've even gotten anything? I would really appreciate any help!
As already pointed out, two things:
You don't need to parse the string when setting the datatype as JSON
Check if the request returned successfully at all
Which could look like this:
$(document).ready(function(){
$.ajax({
dataType: 'json',
success: function(json) {
console.log(data);
},
error : function(xhr, text) {
console.log('An error occurred', xhr, text);
},
url: 'http://www.site.com/mystuff.php'
});
});
When setting the datatype to JSON you also have to make sure that mystuff.php sets the Content-Type header to application/json:
<?php
header('Content-Type: application/json');
?>
No need to parse to json again.. you can directly use the object
Also add the error Function to keep a check if you are getting any error..
$(document).ready(function(){
$.ajax({
dataType: 'json',
beforeSend : function() {
console.log('Before Ajax Request Starts !!');
},
success: function(data) {
console.log(data);
alert(data);
document.write(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Error occurred: " + errorThrown);
},
beforeSend : function() {
console.log('Ajax Request Complete !!');
},
url: 'http://www.site.com/mystuff.php'
});
});
This makes sure you have feedback at every step..
I have a problem to refresh a bloc in my page.
Here is the request:
> $("#pwd_lost_link").click(function(){
alert('1');
$.ajax({
type : 'POST',
url: 'test.php',
dataType: 'json',
data :{"nom" : "akbar"},
success : function(data){
$("#main_bloc").append(data.msg);
alert('2');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert(errorThrown); }
}); })
and here is the php file
<?php
$return['nom'] = "ffrfrfrfr";
echo json_encode($return)
?>
It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded
Thanks
Michaƫl
Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:
In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(data) {
// parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
},
error: function (xhr, status, error) {
// XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
// check for errors ex. alert(xhr.statusText);
}
});
On the PHP side, you may want to debug there to see what is being received and what you are sending back.
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.
$("#pwd_lost_link").click(function(e) {
e.preventDefault();
alert('1');
$.ajax({
...
});
If you aren't seeing the '1' being alerted then that is definitely your first problem.
You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.