How to send an Object with jQuery's .post() function? - javascript

var itemsObj = new Object();
itemsObj.data = "Something";
$.post("somewhere.php", itemsObj, function(data) {}, "html");
Normally, as stated in the API, I'd use { data: "something" } where itemsObj is, but since my object is dynamic and requires a for-loop, I didn't want to get too 'dirty' with a for loop within the data: ... part...
Anyways, the code I wrote above doesn't work. I think maybe I should've apply the JSON.stringify() function on it, correct if I'm wrong?

Add data to itemsObj like this...
var itemsObj = {};
itemsObj['Firstdata'] = "Something";
itemsObj['Seconddata'] = "Something else";
etc... You can use looping to do that...
Then post using $.post("somewhere.php", itemsObj, function(data) {}, "html"); and it should work...

You can use JSON:
$.post("somewhere.php", "param="+JSON.stringify(itemsObj), function(data) {}, "html");
Then in server side:
$obj = json_decode($_POST["param"]);

Related

Writing specific value from database to HTML via AJAX/jQuery

First time question, hoping for some advice:
Code on webpage:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response);
}
});
});
});
};
</script>
</form>
This returns a string that I would like to work with that looks like this:
Answer:
[{"id":"1","answer":"Pull logging","question_id":"5","feature_id":"1","answer_id":"9"}]
Ideally what I would like to do is only select the 'value' to the maxmail_answer 'key' (hopefully those are the right terms?) to the webpage instead. Right now there is only one value but there will be more in the future so something that could parse this string for a specific key and only output those values.
Visually I would see:
Answer: Pull logging ( and then another Answer: for each value I pull out )
First time ever using this site and these languages so total noob and would appreciate some guidance.
Thanks!
You do not to stringify the JSON response, you can get the value of the key you want using the object notation . as follows:
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
//var response = JSON.stringify(data); // no need for this line
$('#response').delay(3600).fadeIn(600);
// catch the answer here
// your result returns within an array so you need to catch the first index
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
});
});
});
};
Besides, ids are unique, you can only access a single element via id selector #, you do not need a .each
What you are receiving from your server is an array of objects in the JSON format. The sample that you have put has the length of "1" and therefore, if want to reach the "id" of the first array, it would be like this:
// var response = JSON.stringify(data); (// don't stringify it!
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+data[0].id);
You need here a loop to go through your array of results and display each result
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$.each(response,function(index,value){//the each loop
$('#response').append("<p>Answer: </p>"+value.answer);//get the answer using . notation
});
}
Json.stringify() returns your javascript object as json data, but i think in your case your response is a json data which you need to manipulate. Json.parse() does this for you and you can access your answer as a property of the javascript object.
success: function(data) {
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
if your json data has multiple result and you need to work through all of them use a loop.
$.each(response,function(index, object){
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+object.answer);
});
First of all. Thank you to everyone who commented on this to help me get started in the right direction. I was able to get what I needed working!! Here is the solution:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#controlpanel:input').each(function () {
var iv = $(this).val();
$('#response').html("");
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var newdata = JSON.stringify(data);
var response = JSON.parse(newdata);
$('#response').delay(3600).fadeIn(600);
$.each(response, function(array, object) {
$('#response').append("<p>Answer: </p>"+object.answer);
});
}
});
});
});
};
</script>
</form>
I needed to parse the data correctly. So I used JSON.stringify to get the data into a string that JSON.parse could use to manipulate the data. But function(index,object) wouldn't work because my output was not an index, but an array. So when changing to function(array,object) this allowed me to get my data just the way that I needed.
Again thanks to everyone for their help!

Empty Array AJAX

So I have searched around a bit in hopes of finding a solution to my problem, but have had no luck.
I am basically trying to pass data into the ajax function, but when it passes it to my php file it only returns an empty array (Yes there are a few topics on this, couldn't find any to fit my needs) , here is the console output: Array ()
Its odd because just before the ajax function I log the data, and it prints out each section with no problems.The posting URL is accurate, works fine straight from my form. I have tried to use response instead of data passed through the function, but no luck their either.
Thanks in advance!
Here is the JS file
$(document).ready(function() {
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
return false;
});
});
And here is my PHP
<?php //removed the issets and other checkers for ease of readability
print_r($_POST);
?>
UPDATE: I have tried to add method:"POST" to my ajax function and it still seems to be printing out blank arrays... Maybe I should convert everything to GET?
jQuery ajax() uses GET as default method. You need to mention method: POST for POST requests.
method (default: 'GET')
$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
Or you can also use post().
EUREKA!!! Wow, the mistake was much simpler than I thought, figured it out solo! Thank you everyone for the tips! Finally got it
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {}; // THIS NEEDS TO BE CHANGED TO BRACKETS!!

Django JS TypeError: data.data is undefined

Why oh Why? I'm trying to create and object with the contents of all of the checkbox status and ids from the HTML page I have.
Why is my data undefined?
function attachskillls(){
var data = {}
$(".checkbox").each(function(){
var obj = {}
obj[this.id] = $(this).prop('checked')
data['data'].push(obj)
})
$.ajax({
type: "POST",
url: "/api/skill/attch/",
data: JSON.stringify(data),
})
}
You have declared data as an object
var data = {}
Now, you are iterating through checkboxes and executing this
data['data'].push(obj)
data['data'] is not an array so data['data'].push will fail.
To achieve this, you could do something like this
var data = {};
data['data'] = []
This ensures that the data['data'] is an empty array. Then follows the rest of the code.
Hope you understand the issue now.

Javascript array into jQuery .post AJAX call

I have a JAVASCRIPT array that looks like this:
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
I'm trying to pass this to an AJAX call via jQuery .post function so that the .PHP file gets it in this format:
$_REQUEST['query']['min_price'] = 120000;
$_REQUEST['query']['max_price'] = 150000;
So far I've tried:
$.post("ajax_findproperties.php", {query: postarray},
function(data){
// processing function with JSON result
}
,'json');
But I've had no luck. I even tried changing the var postarray to query and then tried query.serialize() in place of the bracketed variable block, but with no luck either.
When I check my status on Firebug, the AJAX call has absolutely no POST vars set whatsoever - complete blank.
The javascript array is not an array, it's an object. Define it before:
var postarray = {};
postarray['min_price'] = 120000;
postarray['max_price'] = 150000;
or replace with:
var postarray = {
min_price: 120000,
max_price: 150000
};
Now the JSON.stringify works:
alert(JSON.stringify(postarray));
Also see this example.
But this object should also be send without JSON.stringify():
$.post("ajax_findproperties.php", {query: postarray}, ... );
Have you tried converting it with JSON.stringify(); and then doing a json_decode(...); in the PHP script?
Try this solution : add [] to your query key
$.post("ajax_findproperties.php", { 'query[]': postarray },
function(data) { },
'json');
Source : http://api.jquery.com/jQuery.post/#example-2

JSON parse issue

I have a JSON string like this:
{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}
How can I parse this using javascript? I have tried using:
function callbackFun(data) {
$j.each(data.result, function(i, item) {
alert(this.time);
});
}
But it seems this is not correct.
If you retrieve that piece of data from $.ajax() then you could set up dataType: 'json' to get it automatically parsed for you.
Otherwise just use $.parseJSON()
If you're using jQuery, it's trivial:
var obj = '{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}';
var json = jQuery.parseJSON(obj);
alert(json.time);
alert(json.countryName);
http://api.jquery.com/jQuery.parseJSON/
Are you looking for this?
var MyJson = '{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}';
var MyObject = jQuery.parseJSON(MyJson);

Categories

Resources