How to pass data while using get method in xdr - javascript

As IE does not support cross domain issues, we have to use get or post method by using xdr, my problem is, I don't know how to pass data while using get method with xdr.
Code snippet for get method using jquery ajax is like -
$.ajax({
type: 'GET',
cache: false,
url: site_url,
data: params,
success: onsuccess,
error:onError
});
but suppose if I write this code for xdr it will be like -
var xdr = new XDomainRequest();
xdr.CacheControl = "no-cache";
xdr.open("get", site_url);
xdr.onload = function () {
var data = $.parseJSON(xdr.responseText);
onsuccess(data);
}
xdr.onerror = function() {alert('err');};
xdr.send();
Now in this, I do not know where to pass data!!!
Please help me out to solve this problem.

It all happens in the ".open" method.
Lets say you want to pass some JSON or an object to the request.
Do it like so...
var my_request_data = {
"whatever" : "whatever",
"again" : "whatever again",
"you get" : "the point..."
};
my_request_data = $.param(my_request_data);
xdr.open("get", "http://url.com/to/get/or/post/too/" + my_request_data);
jQuery turns the JSON object into URL friendly params and then it is sent to the server.
That is how you pass data!

Related

Add data to JQuery Form

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();
});

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!!

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}}

requested json parse failed ,there was an error parsing the json document

var objectData ={
"emailAdress" : document.getElementById('emailAddress').value ,
"password": document.getElementById('password').value }
var objectDataString = JSON.stringify(objectData);
alert(objectDataString);
var url = "url";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert('connected..');
}
};
xmlhttp.open("POST",url,true);
xmlhttp.send(objectDataString);
$.ajax({
type: "POST",
URL:"login.php",
contentType:"application/json",
CrossDomain:true,
data: JSON.stringify(objectData),
dataType: 'json',
success: function (data) {
alert("success");
var ret = jQuery.parseJSON(data);
alert(ret);
I have login form which contains userid and password.i have to convert that user entered info into json and send it to the server.but getting json parsed error .unable to find the error.please tell me where i m doing wrong..?i m trying from so many hours but unable to find .
Ignoring the XHR code, and just looking at the ajax call:
There's no CrossDomain option. There's a crossDomain option, though. (JavaScript is case-sensitive.) You probably don't want that option at all, though, with the URL you're giving.
You're telling jQuery that the data coming back is JSON. That means jQuery will parse it for you before giving you the data argument to your success function. You don't need (or want) to call JSON.parse on it, that's already been done for you. data will be parsed data.

Setting object properties using AJAX

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]?

Categories

Resources