Javascript array into jQuery .post AJAX call - javascript

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

Related

Load a JSON file into a JS object

I try to load a json file into a JavaScript var but it just doesn't work out.
var jsonString = JSON.stringify('./test.json');
var obj = JSON.parse(jsonString);
console.log(obj.details.ProductID);
it says that it can't read property ProductID of undefined.
What am I doing wrong here ?
You need to make an AJAX call to get the file. $.getJSON was intended for exactly this purpose:
$.getJSON('./test.json', function(obj) {
console.log(obj.details.ProductID);
});
If you are using jQuery:
$.getJSON( "/test.json", function( obj ) {
console.log(obj.details.ProductID);
});
JSON.stringify() first argument needs to be a valid JSON string, not a file.
You need to use AJAX to retrieve file from server:
$.getJSON('./test.json', function(responseObject){
var obj = responseObject
console.log(obj)
})
In case it helps anyone, just use this:
const dataObjectFromFile = require('./path/to/datafile.json');

How can I send parameters to php script (with ajax) so that they will be included on the server side?

I have the following function:
function myFunction () {
$.getJSON('remote.php', function(json) {
var messages = json;
function check() {
...
and I call there the remote.php script which makes a simple select query and returns all data with json.
I would like to pass a parameter to this query called time, which will be filled earlier in my code by:
var actualTime = new Date(params);
I know that on php script I have to do:
$time = $_POST['time'];
but how should I modify my jquery then to pass this argument further?
Just pass an object to $.getJSON. It will be sent to PHP as $_GET.
$.getJSON('remote.php', {
time: actualTime.toJSON()
}, function(json) {
var messages = json;
});
Then your date will be in PHP as $_GET['time']. I'd suggest converting to a DateTime object so you can format it as you need.
$time = new DateTime($_GET['time']);
If you want to use $_POST instead, then you'll have to change to using $.post.
$.post('remote.php', {
time: actualTime.toJSON()
}, function(json) {
var messages = json;
}, 'json');

How to use ajax filter

I'm trying to filter out some values from an AJAX call. Here's what I have tried:
var year = 200908; // for example
var resultArray = data.filter(function (a) {
return a.proddate == year;
});
var firstTask = resultArray[0];
var lastTask = resultArray[resultArray.length - 1];
data is coming from success function in an ajax call. But I'm getting this error:
JavaScript runtime error: Object doesn't support property or method 'filter'
Here is a sample of the returned data:
"[{
"tasknum":6,
"dependtask":5,
"jobname":"prc",
"proddate":"200908",
"activity":"Pr‌​elim",
"groupname":"CNSPROD-EST",
"parametername":"n/a",
"parametervalue":"n/a"
}]"
Any ideas?
First, try doing a console.log on data and verify what exactly you're retrieving. filter only works on arrays so this would work:
var resultArray = [1,2,3].filter(function(a) {
return a > 2;
});
But this will not:
// "Object doesn't support property or method 'filter'"
var resultArray = {1: true, 2: true, 3: true}.filter(function() { ... });
I suspect that data is not the variable assigned to the response. Or perhaps you haven't parsed response to js array from JSON using JSON.parse()
Your code works fine here:
DEMO

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

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

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"]);

Categories

Resources