using $.post has character limits? - javascript

I am using jquery $.post method to send a string to a servlet.
var temp = "hsad d jad a....sad";
var str="testServlet?param="+temp;
$.post(str, function(data) {
alert("saved");
});
testServlet receives a call when the temp has less characters, say 5000. But when it has more no. of characters i.e. > 5000 it is not called. Firebug says 'Aborted'.
I could not understand why.
I thought that this might be because the above code is sending temp in the get form so I wrote like this -
var temp = "hsad d jad a....sad";
var str="testServlet";
$.post(str, {param:temp}, function(data) {
alert("saved");
});
But in this case the servlet was called but param was null.
1. Is there any difference between the above two methods ?
2. If first method is get then why jquery has $.get ?

There are limitations on maximum URL length, depends on web browser, webserver e.t.c.
When your pass some parameters in url will have problem with too long parameters even if your use POST request.
In your code only {param:temp} will be stored in request body. str is url so it's has max length restriction.

Related

Check contents of response to json request?

I am trying to build a random quote generator as per the FreeCodeCamp challenge, but I wanted to begin by just writing a test to confirm I'm actually getting the json object I'm requesting. I have a simple h1 element with the id set to 'quote' and the following code (jQuery is loaded up in the CodePen)
function genQuote () {
var output = $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(data){
var theQuote = data.content;
var Author = data.title;
document.getElementById('quote').innerHTML = theQuote;
});
}
The url in question, when visited, shows what looks plainly like a json object, to me, but my function does not change the #quote item at all.
Remove &callback= from URL, to request JSON, instead of converting $.getJSON() call to jsonp request. Also, an array is returned, not a plain object; access the object using bracket notation
function genQuote () {
var output = $.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(data){
var theQuote = data[0].content;
var Author = data[0].title;
document.getElementById('quote').innerHTML = theQuote;
})
}
$(genQuote);
jsfiddle https://jsfiddle.net/gpyx6jLy/
As the comment to your question says, this is a Cross Origin Request Sharing (CORS) issue. The API is returning "http://null" as the Access-Control-Allow-Origin header, which disallows your access.
It looks like this is a bug in their API server, and you probably won't be able to use it.

AJAX and a global variable not working, have I got this wrong?

what I am trying to achieve is to AJAX a load of client's data into a page (this works), I then have a company ID in one of the fields brought in. I need to cross check this with a different company table (same database) to replace the company ID on the page with the name instead.
To get this I have set a global javascript variable to blank then fired off the main AJAX request getting all the initial client data then within that parsing loop (client side) I need to fire off a function which will check against the companies table to get the name. My current problem is that the global variable is not being set to the 2nd AJAX result. Here is my code:
var nameresult = "";
function namecheck(id){
var request = new Ajax().sendRequest
('../company_check.php',
{ method: 'GET',
parameters: 'id=' + id,
callback: namecheckReceived }
);
}
function namecheckReceived(xmlHTTP){
var n_data = JSON.parse(xmlHTTP.responseText);
nameresult = n_data[0].name;
}
function client_call(){
var request = new Ajax().sendRequest
('../client_data.php',
{ method: 'GET',
callback: searchReceived }
);
}
function searchReceived(xmlHTTP){
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.length; i++)
{
namecheck(data[i].company_id);
/////spit out all the data in a readable format //////
}
}
Notes:
Only one result will be received from the company_check.php hence no
loop in the namecheckRecieved() function.
No errors in the JS console.
The nameresult variable stays as blank and is never
changed, if I alert(nameresult) within the namecheckRecieved()
function it spits out what I want so why is it not changing the
global variable with each loop of the searchRecieved() function?
I'm going to delete all my previous comment and say that you only need one ajax call. And everything should be done on server side. That means get the company Id, and use that to get the name of the company then pass everything back to the client side. From the look of it you are doing A LOT of call backs to the server to get every company name when you could have just done that on your first visit to the server. This way you do not need to worry about doing two ajax call Although from the look of it your doing more than 2 calls, depending on the length of data
Try this
function namecheckReceived(xmlHTTP){
var n_data = JSON.parse(xmlHTTP.responseText);
nameresult = n_data[0].name;
client_call();
}

$.get with dynamic data names?

I am having an issue trying to set the data name or the objects being passed in. I am writing a system that uses AJAX to send requests to the server which then returns the necessary data. However, I am trying to make things generic to where if the developer adds more "slates" then it will automatically send the request on its behalf. The code looks as following:
$(document).ready(function() {
$(".slate").each(function(){
$.get("requests.php", { $(this).attr('name') : "true" }, function(data){
});
});
});
in other words it takes the name of the element and applies it to the query string. JavaScript doesn't seem to like the
$(this).attr('name')
in the syntax which is understandable since it expects just text (not a var or a string). Is there a way to make this work? Any help is greatly appreciated!
$(document).ready(function() {
$(".slate").each(function(){
var data = {};
data[$(this).attr('name')] = "true";
$.get("requests.php", data, function(data){
});
});
});

How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});

jsonp request not working in firefox

I am trying a straightforward remote json call with jquery. I am trying to use the reddit api. http://api.reddit.com. This returns a valid json object.
If I call a local file (which is what is returned from the website saved to my local disk) things work fine.
$(document).ready(function() {
$.getJSON("js/reddit.json", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
If I then try to convert it to a remote call:
$(document).ready(function() {
$.getJSON("http://api.reddit.com", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
it will work fine in Safari, but not Firefox. This is expect as Firefox doesnt do remote calls due to security or something. Fine.
In the jquery docs they say to do it like this (jsonp):
$(document).ready(function() {
$.getJSON("http://api.reddit.com?jsoncallback=?", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
however it now stops working on both safari and firefox. The request is made but what is return from the server appears to be ignored.
Is this a problem with the code I am writing or with something the server is returning? How can I diagnose this problem?
EDIT Changed the address to the real one.
JSONP is something that needs to be supported on the server. I can't find the documentation, but it appears that, if Reddit supports JSONP, it's not with the jsoncallback query variable.
What JSONP does, is wrap the JSON text with a JavaScript Function call, this allows the JSON text to be processed by any function you've already defined in your code. This function does need to be available from the Global scope, however. It appears that the JQuery getJSON method generates a function name for you, and assigns it to the jsoncallback query string variable.
The URL you are pointing to (www.redit.com...) is not returning JSON! Not sure where the JSON syndication from reddit comes but you might want to start with the example from the docs:
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function (data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#redditbox");
if ( i == 4 ) return false;
});
});
});
(apologies for formatting)
EDIT Now I re read your post, I see you intended to go to api.reddit.com unfortunately you haven't got the right parameter name for the json callback parameter. You might need to further consult the reddit documentation to see if they support JSONP and what the name of the callback param should be.
I'm not sure about reddit.com, but for sites that don't support the JSONP idiom you can still create a proxy technique (on the backend) that would return the reddit JSON, and then you would just make an ajax request to that that.
So if you called http://mydomain.com/proxy.php?url=http://api.reddit.com:
<?php
$url = $_GET["url"];
print_r(file_get_contents($url));
?>
http://api.reddit.com/ returns JSON, but doesn't appear to be JSONP-friendly. You can verify this, if you have GET, via
% GET http://api.reddit.com/?callback=foo
which dumps a stream of JSON without the JSONP wrapper.
http://code.reddit.com/browser/r2/r2/controllers/api.py (line 84) shows the code looking for 'callback' (not 'jsoncallback'). That may be a good starting point for digging through Reddit's code to see what the trick is.

Categories