I want to send a very long string to a servlet. Could be more than 10,000 characters.
I want to know which jquery ajax/ or any way to send it to the servlet.
I have used $.post and faced characters limit problems.
sending long strings in jquery post
using $.post has character limits?
Did you send the string as part of the URL (GET) or did you send the string as part of the POST body?
Use this to send it as POST:
$.post(url, {longString: veryLongString}, function(){});
$.post is just an alias for $.ajax (with the method param preset) => it won't make any difference which of these methods you will use.
In case there is any doubt left in your mind here:
function ajaxTest () {
var longstr = "qwertyuiopasdfghjklzxcvbnm";
while (true) {
longstr += longstr;
if (longstr.length > 100000) {
break;
}
}
console.log(longstr.length);
$.ajax({
url: '/ajax',
type: 'post',
data: longstr,
processData: false,
success: function (reply) {
console.log(reply);
}
});
}
I set the server up to reply with "ok" + the length of the post data received. The first console log reports "106496", the second one "ok 106496".
There is no client side limit (eg, imposed by jquery) to how much data you can send via post.
As far as I know there are no character limitations on a POST request. GET has limitations, but I cant recall any on POST operations.
In the above links (the ones you made reference to):
$.post(
"TestServletAsh?xml="+str,
function(data) {
alert("mission successfull"); //nothing to do with it or data here in this SO question
}
);
sends the variable 'str' as a get parameter.
The way to send data to a POST request using jquery is
$.post(url, {data:'whatever you want blah blah blah'}, function(data){});
there is no limit in post, check your js code, you have some mistake or using the get method instead of post
Related
I have an array in JS and I am trying to pass it as parameter to URL and catch it in PHP but I cant get to understand how to do it:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
FYI: I am using windows.fetch for posting.
in PHP:
$trafficFilters = $_GET["trafficFilters"];
$obj = json_decode($trafficFilters);
var_dump($obj);
You are passing the data to php with fetch() intead of ajax, so the alternative of my first answer to do the same with the fetch() is:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var trafficFilterHolderJoin = trafficFilterHolder.join(); // comma-separeted format => "roadworks,snow,blocking"
Now add the trafficFilterHolderJoin variable to the traffic query of the URL of your fetch(), like:
fetch('script.php?traffic=' + trafficFilterHolderJoin)
Then in your php script file you will convert the comma-separeted format to php array format using the explode function:
$traffic = explode(",", $_GET['traffic']);
It's quite simple, you are passing these data to php with ajax, correct?
First of all, you are creating the javascript array incorrectly:
var trafficFilterHolder = [0: "roadworks", 1: "snow", 2: "blocking"];
Don't use brackets to create arrays with keys, use this format instead:
var trafficFilterHolder = {0: "roadworks", 1: "snow", 2: "blocking"};
Now, in the ajax, just add the array in the data:
$.ajax({
data: { trafficFilters: trafficFilterHolder }
});
All demands to the server are executed as an http requests. Ther are two types of HTTP requests - GET and POST.
https://www.w3schools.com/tags/ref_httpmethods.asp
What you're describing is called GET request. With GET request the parameters are passed via the address bar. For making an http request you have two options.
The direct HTTP GET request.
For this you need simply open a new page with
window.location.href = 'http://your_site.com/file.php?name1=value1&name2=value2'
This will open a new page in your browser and pass a request with your parameters.
An Ajax HTTP GET request.
You have a lot of options here:
an old-fashion way with xmlHttpRequest object
a modern fetch API with promises
third-part libraries like jQuery.ajax etc.
AJAX request can send and receive information from the server (either in GET or POST request) without renewing the page. After that the result received can be managed with your javascript application however you want.
Hope, it makes more clear for you. You can search about all this technologies in the google. This is the way how to exchange data from front-end to back-end.
Try using ajax and pass that array and retrieve values at the PHP end.
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
$.ajax({
type: "POST",
url: "test.php",
data: {data : filters},
cache: false,
success: function(){
alert("OK");
}
});
I want to get the value of my checkbox in Ajax so that I can save it in database as a preference for each of my user. I've never done AJAX before so i'm quite lost about it.
My javascript file :
$(document).ready ->
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'click', (e) ->
E.accounts.changeUnmarkVisibility()
$('#label-letters-visibility').on 'click', (e) ->
if $('#letters-visibility').is(':checked')
$('#letters-visibility').prop('checked', false)
else
$('#letters-visibility').prop('checked', true)
E.accounts.changeUnmarkVisibility()
$('#letters-visibility').on 'change', (e) ->
$.ajax
url: "/backend/accounts/{#id}"
type: 'POST'
data:
isChecked: $('#letters-visibility').is(':checked')
success: (data, status, request) ->
console.log data
E.accounts =
changeUnmarkVisibility: ->
unmarkLines = $('.active-list .unmark').closest('tr')
if unmarkLines.is(':visible')
unmarkLines.hide()
else
unmarkLines.show()
)
My post request send me back a 404 error, I think the error is in my 'Data' option
Yeah Deckerz is right normally you have an ajax call which has a 'Data' option and then a success option. The data is an array/object of values that you want to send.
There are lots of options on the jquery ajax page and it's quite easy to get lost in them. This though is the norm. Done is called after some.php (in this case) has finished and msg has the data that is sent back from msg. Normally you'll want this in a json format. This is good practise for if you want to send back 2 variables. e.g Status (success/error) and ErrorMessage = ""
if you're using php json_encode is the function to use to achieve this.
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I'm not sure I've understood where you're stuck at: it seems to me you've already read the checkbox's value without problems, so I'll assume you don't know what to do with the AJAX call.
The AJAX call is really just a request to your server: you probably want to call a script (pointed to by the URL you pass), with the parameters you need to identify the user and the option, that writes the checkbox's value to the database.
One thing that may be useful to know: you don't need to construct a query string to pass your parameters along with a GET request, you can just pass them in the data parameter of the jQuery.ajax call as a regular JSON object.
AJAX doesn't do that. AJAX returns the value. And then you look at the value to decide what to check. If you are doing this in jquery, then look here: https://api.jquery.com/checked-selector/
I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever¶m2=whatever¶m3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'¶m2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo¶m2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.
Hi I am quite new to jquery and web programming in general.
My question is how to send hidden query parameters using a post request in jQuery and Retreive the data from the post request in another. I know that there are a lot of tutorials on .post in jQuery but I cant seem to find any on .get requests (if that is what I need here)
For example in one .js file for one page I have
$.ajax({
type: 'POST',
url: 'url',
data: {
'startDate': this.options.startDate,
'endDate': this.options.endDate,
'selectedReport': this.options.endDate,
},
success: function (msg) {
alert('wow' + msg);
}
});
but in another js file for another page I want to have like a get request that retrieves these parameters.
Could anyone explain how would I write this get request in the js file to retrieve them?
Thank you for the help
It seems to me that POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
.ajax() POST data is send as query string parameters. In the other page you can write javascript to fetch these query string values.Below is sample to read query string values:
(function ($) {
$.QueryString = (function (a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p = a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'))
})(jQuery);
You can the above function like below:
var startDate=$.QueryString["startDate"];
https://api.jquery.com/jQuery.ajax/
With your current function you are sending POST data to the otherside.
For example, in PHP, data sent will be in the $_POST array.
To set a GET request you just have to set type from POST to GET
type: 'GET'
Then on the PHP side data sent will be in $_GET array.
I realized that JavaScript post request like a form submit answers my questions because it is more client side although the ajax is server side. thank you for all of the help!
I had a problem with jquery's post api.
$(".MGdi").click(function () {
id=$(this).attr("rel")
$.post( 'Mdeger.asp?cmd=MG', { id: id, drm: $(this).html()} ,
function( data ) {
var $response=$(data);
var snc = $response.find('#snc').html();
alert(snc);
},"application/x-www-form-urlencoded");
});
Another way is:
$(".Pasif").click(function () {
id=$(this).attr("rel")
$.post( 'Mdeger.asp?cmd=Pasif', { id: id, drm: $(this).html()} ,
function( data ) {
$(this).html(data);
alert(data)
},"application/x-www-form-urlencoded");
});
Everything is OK on serverside but clientside's success function does nothing.
Even basic codes like alert("hoho"); success not triggering.
this usually happens when respond couldn't be parsed. you should check the respond using firebug or similar debugging tool.
especially the methods that expects json data, strictly validates the respond and if there is anything invalid it just does nothing, no-error, no-warning, no-exception.
when your callback function doesn't run, you should suspect that your respond isn't correct.
// Türkçe özet
uzun lafın kısası dönüş değerinde bir terslik varsa dönüş fonksiyonu çalışmayacaktır. sunucudan gelen değerleri iyice kontrol etmekte fayda var. jquery dönüş değerinde veya dönüş fonksiyonunda bir hata olursa seni uyarmadan işi sonlandırıyor.
I had this problem as well. It turns out I was making an AJAX call to the same domain, but on a different port, which is not allowed (for security reasons) in Javascript.
See this relevant question for more info:
How do I send an AJAX request on a different port with jQuery?
I was very surprised that the AJAX call would POST/GET to the server, (which I was able to verify by looking at the server log) but that the response was never read. I would have thought that both sending and receiving would be disallowed.
I had this error too, and that was a stupid problem : I set dataType to "json" in my JS, but the page called was returning plain HTML. And this cause to not fire the success function at all.