First of I admit that I am really bad at js and just got started. I have this snippet in the repository:
function sendReport() {
$.post($('#reportForm').attr('action') + '/post', $("#reportForm").serialize()).done(function() {
reportManager.run();
});
}
And I want to add data to it. I want the webservice that is receiving the post to receive an additional key/value-pair. I tried something like
var data = $('#reportForm').serializeArray();
data.push({name: 'stuff', value: 'blaha'});
$.post(data, $("#reportForm").serialize()).done(function() {
reportManager.run();
});
Didn't work at all and I would really appreciate any help with this.
EDIT:
Tried doing the suggestion below, didn't work. Tried this just to verify that the new parameter didn't ruin anything:
//data to post
var data = $('#reportForm').serializeArray();
//url to post
var url = $('#reportForm').attr('action') + '/post';
//options required for jQuery.post
var options = { "data":data, "url": url };
$.post(options).done(function() {
reportManager.run();
});
That doesn't work. I'm getting an error like this on the server:
noHandlerFound No mapping found for HTTP request with URI [/[object Object]]
I am considering that something else in the code might be using some implicit behaviour, but I find it strange that trying the code above(without even adding new data) can break the current working behaviour.
You are not providing uri parameter for post method, you should use something similar to:
//data to post
var data = $('#reportForm').serializeArray();
data.push({name: 'stuff', value: 'blaha'});
//url to post
var url = $('#reportForm').attr('action') + '/post';
//options required for jQuery.post
var options = { "data":data, "url": url };
$.post(options).done(function() {
reportManager.run();
});
Related
So I'm having some trouble with my code. It seems that when I get the reCAPTCHA response it loads when I alert the variable, but AJAX isn't wanting to get it.
var url="";
if (DEPOSIT) {
url = "/get_inv?" + opts;
} else {
var g = grecaptcha.getResponse();
url = "/get_bank_safe?g-recaptcha-response=" + g;
}
alert(url);
$.ajax({
"url": url,
success: function(data) {
try {
alert(data);
data = JSON.parse(data);
Yes I've gotten a valid response from the URL variable itself, but when announcing the AJAX variable 'data', nothing is persevered. Therefore JSON cannot parse 'data'.
It even states that "url" : url.
So I'm not sure how to go about this. If there is any solution please alert me of so.
Thanks! ~LTn | mrgreen33gamer
I have working on a webpage that displays json data in a html hierarchical structure, using the jQuery plugin json2html.
Currently the json data is entered into a text area and a button is pressed to run the conversion. This is the current function that gets the json from the text area and starts the conversion.
$('#btnVisualize').click(function() {
//Get the value from the input field
var json_string = $('#inputJSON').val();
try
{
//json
//var json = JSON.parse(json_string);
eval("var json=" + json_string);
visualize(json);
}
catch (e)
{
alert("Sorry error in json string, please correct and try again: " + e.message);
}
});
The api that the data is comming from needs a lot of authentication, so I have a seperate javascript file that generates the authenticaton and creates the full url to load the api.
function generateUrl(itemkey) {
var orig = "http://explorerapi.barratthomes.co.uk/v2.0/development/getbyitemkey?ItemKey="+itemkey+"&";
Auth.Auth = createAuth();
var var_pairs = [
{name: "Auth.Utc", val: encodeURI(Auth.Auth.Utc)},
{name: "Auth.RequestId", val: Auth.Auth.RequestId},
{name: "Auth.DeviceId", val: Auth.Auth.DeviceId},
{name: "Auth.Hash", val: Auth.Auth.Hash}];
for(var i=0; i<var_pairs.length; i++) {
orig += (i==0?"":"&")+var_pairs[i].name+"="+var_pairs[i].val;
}
var var_names = ["BrandCode", "ApplicationId", "ApplicationVersion", "LanguageCode", "IsPublished", "MarketingSuiteDevelopmentId", "UserLocation", "Os", "ScreenResolution", "Hierarchical"];
for(var j=0; j<var_names.length; j++) {
orig += "&"+var_names[j]+"="+Auth[var_names[j]];
}
return orig;
}
This is the function that generates the url.
I need to take the url from that function and connect to the api and pass the data directly to the json2html function, so I no longer have to paste the json data into the text area.
I have been looking at $.getJson and $.parseJSON but having no luck, I'm not sure where to go next?
Try this Jsonp to do the fetching the data from the url
function insertIntoTextArea(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'your proper url?callback=insertIntoTextArea';
// insert script to document and load content
document.body.appendChild(script);
You should be able to use $.getJSON like this
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
And then just pass the data object to json2html. However, check with the API that you're connecting to http://explorerapi.barratthomes.co.uk/v2.0/development/getbyitemkey as they might require JSONP (which pretty much just performs a callback function to get around CORS).
See http://api.jquery.com/jquery.getjson/
If the URL includes the string "callback=?" (or similar, as defined by the >server-side API), the request is treated as JSONP instead. See the discussion >of the jsonp data type in $.ajax() for more details.
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}}
I tried searching around the web but couldn't fix my problem with the answers.
I have two node js servers running on my localhost.
Backend: localhost:9000
Frontend: localhost:3000
I have a jquery Ajax call in my frontend server which looks like this:
$(document).ready(function() {
$.ajax({
url: "http://localhost:9000/merchant",
type: "post",
data: {content: "{"+
'"0": {"name":"kfc", "desc":"great chicken", "web":"www.kfc.com"},'+
'"1": {"name":"pizzaexpress", "desc":"your favourite pizza express", "web":"www.pizzaexpress.com"},'+
'"2": {"name":"indianmasala", "desc":"great indian food", "web":"www.masala.com"},'+
'"3": {"name":"starbucks", "desc":"all coffeee", "web":"www.starks.com"}'+
"}"}
}).done(function(data) {
alert(data);
});
});
Yes, I post a JSON in content parameter. Which is getting stored in my mongoDB and should be returning the inserted ids.
My backend app.post function looks something like this:
var content = JSON.stringify(req.body.content);
content = JSON.parse(req.body.content);
var ids = new Array();
for (var key in content) {
if (content.hasOwnProperty(key)) {
var merchant = new Merchant();
merchant.name = content[key].name;
merchant.desc = content[key].desc;
merchant.web = content[key].web;
merchant.save();
ids[key] = merchant._id;
}
}
var response = {"status":"Request processed successfully", "id": ids};
console.log(JSON.stringify(response));
res.contentType('json');
res.send(JSON.stringify(response));
When I load the frontend localhost:3000 on my browser the AJAX calls the localhost:9000/merchant which then stores the merchant information in mongodb but neither
res.send();
nor
res.write();
send the response. I checked the console.log for the JSON.stringify(response) which looks fine.
My response is empty when I see it in firebug.
Not sure what going wrong. Much appreciate if you lot give me an answer.
Many thanks.
I am newbie in OOP and I try to build an object using ajax request. What I need is to get 'responseArray' in JSON format and than work on it.
function adres(adres) {
this.adres_string = adres;
var self = this
$.ajax({
type: 'POST',
url: "http://nominatim.openstreetmap.org/search?q="+adres+"&format=json&polygon=0&addressdetails=0",
success: function(data) {
self.responseArray = eval('(' + data + ')')
}
})
//Method returning point coordinates in EPSG:4326 system
this.getLonLat = function() {
var lonlat = new OpenLayers.LonLat(this.responseArray.lon, this.responseArray.lat);
return lonlat;
}
}
The problem starts when in appilcation code I write:
var adr = new adres('Zimna 3, Warszawa');
adr.getLonLat();
This returns nothing as there is no time get the response from the server.
How to write it properly in the best way? I've read about when().then() method in jQuery. This may be OK for me. I just want to get know best practise
This is how AJAX works (notice the A-synchronous part). You are right, the moment you call adr.getLonLat() response did not yet came back. This is the design I would suggest: just pass callback function reference to adres constructor:
function adres(adres, callbackFun) {
//...
success: function(data) {
var responseArray = eval('(' + data + ')')
var lonlat = new OpenLayers.LonLat(responseArray[i].lon, responseArray[i].lat);
callbackFun(lonlat)
}
and call it like this:
adres('Zimna 3, Warszawa', function(lonlat) {
//...
})
Few remarks:
adres is now basically a function, you don't need an object here.
do not use eval to parse JSON, use JSON object.
Are you sure you can POST to http://nominatim.openstreetmap.org? You might hit the same origin policy problem
where is the i variable coming from in responseArray[i]?