jquery ajax call fails when data size exceeds 1119 bytes - javascript

A button click triggers this code:
$("#testButton").click(function() {
var str = $("#ptext").html();
$.ajax({
type: "POST",
url: "/pages/testfn",
data: { thetext: str }
})
.done(function(msg) {
alert( "success " + msg );
});
});
The php that handles this is this:
public function testfn() {
$s = $_POST['thetext'];
echo strlen($s);
}
This works perfectly if the amount of text I have in the #ptext div is less than 1120 bytes. More than that and it silently fails. How can I pass more than 1120 bytes to the testfn function?

Check your PHP configuration. This is most likely a configuration issue. Try fiddle with the values below in your php.ini:
post_max_size=32M
upload_max_filesize=32M
memory_limit=32M
32M (megabytes) is just an example, you might want to have other values.

Well, this is embarrassing. I discovered the problem only occurred when I was testing the site through a proxy server. To get at the site from the "outside" I used a Netshade proxy server in Canada. The clue was that the POST worked when I tested it with my cell phone browser. So I used the local IP address and turned off the proxy server and it all works.

Related

jQuery how to return value without encoding it?

I have a problem with encoding/decoding some text.
On my page I have a picture:
<img id ="pcs" src="xxx.jpg" game="Hellblade: Senua’s Sacrifice ">
Then use ajax to send data to php server:
$('#pcs').click(function(){
if($(this).attr('src') == "xxx.jpg" ) {
$(this).fadeOut(100, function() {
var cookie = "dummy";
var game = $(this).attr('game');
$.ajax({
url: "http://example/notif_games.php",
type: "POST",
data: ({'cook_':'cookie', 'game_': game}),
});
The problem is the data are somehow encoded and recieved as: Hellblade: Senua’s Sacrifice
Instead, I need it to be recieved as: Hellblade: Senua’s Sacrifice
Even where I try
var game = $(this).attr('game');
alert(game);
it returns the 'encoded' value.
It's needed with the ’ part because I then put it in DB and compare it with another tables where the value is with the ’.
This is a browser issue and not a jquery one. Your browser is rendering the text already before jquery touches it. You need to decode it on the server side when you ajax it up.
With php you can do $data = htmlentities($data);

Ajax doesn't work anymore on the prod server

I'm a web developper in a small company that decided to make its selling website in PHP5/Laravel 4.2 instead of Prestashop or anything else. The site is hosted by another company, and we don't have the liberty to make anything we'd want on the server.
I made 6 monthes ago a script in AJAX that let the user know without refreshing how high would his shipping fee and taxes cost. We're in Europe in the border of France and Switzerland, so it's really a necessity to have this script. It worked really great, until this week when I wanted to implement another script, and found out that this script didn't work anymore (for how long, I don't know).
The JS :
function shippingFee()
{
var idCountry, weight;
weight= document.getElementById('weight').value;
idCountry = document.getElementById("country").value;
$.post('ajax/shippingFee',
{idCountry: idCountry, weight: weight},
function(data){
obj = JSON.parse(data);
$('#fee).html(obj.fee);
$('#total').html(obj.total);
$('#sub').html(obj.sub);
$('#promo').html(obj.promo);
});
};
Here is my route :
Route::post('ajax/shippingFee', 'AjaxController#shippingFee');
Here's my function (not everything, just the final result) on the AjaxController:
public function shippingFee(){
//Test values, only for this example
$fee = 12;
$total = 24;
$sub = 3;
$promo = 0;
$res = ['fee'=>$fee, 'total'=>$total, 'sub'=>$sub, 'promo'=>$promo];
echo json_encode($res);
}
When I click on the button that activate the function, I have this error :
SyntaxError : unexpected token in json at position 0
And if I click on the source, I have my JSON :
{"fee": 12, "total":24, "sub":3, "promo":0}
Again, the code worked perfectly six monthes ago, and still works on localhost. Do you have any idea on what's happening ?
Thanks a lot.
specify the dataType in Post request, also check the response result in Developer tools that will give you clear idea. don't forget to call exit(0) method once you echo result that will fix the issue if you using any framework
PHP Exit method
Okay, I succeeded. I don't know why, but my json_encode wasn't sending a satisfying json. I tried to change the structure of my function with this :
function shippingFee()
{
var idCountry, weight;
weight= document.getElementById('weight').value;
idCountry = document.getElementById("country").value;
$.ajax({
url: "ajax/shippingFee",
type: "Post",
data: {'idCountry':idCountry, 'weight':weight},
traditional: true,
success: function (data) {
data = JSON.stringify(eval('('+data+')'));
var obj= JSON.parse(data);
$('#fee).html(obj.fee);
$('#total').html(obj.total);
$('#sub').html(obj.sub);
$('#promo').html(obj.promo);
}
});
};
Thus, with the data = JSON.stringify(eval('('+data+')')); I say that this is a JSON. And my code is working like a charm. I found this solution by watching this post : Convert object string to JSON
I tried to put the dataType:"JSON" before the success, but when I did it returned an error. With contentType:"application/json" I had an error 500.
Thanks to the people who answered me :)

AJAX and JSON error handling

I have a form which submits data via AJAX to an external server.
The data which gets sent is then validated and if correct the user can then advance onto the next step of the form.
If the data is not valid, then the server returns an error which is outputted as a JSON object.
I can see the JSON object in FIDDLER.
My aim is to grab that JSON data and output it on the page and notify the user.
Ideally, i would do this as part of an error handler on the AJAX request(found below).
Is this achievable?
PS:
Unfortunately, I can't set up a demo because the link that the data is posted to is only available on my network.
It is also worth pointing out that the error that the back-end script outputs is actually stored in the link that the data is posted to.
AJAX REQUEST:
var setUpVrmData = function() {
$("#getvrmdata").click(function () {
var p_vrm = $('#p_vrm').val();
$.ajax({
dataType: "JSON",
type: "POST",
url: "http://217.35.33.226:8888/l4_site/public/api/v1/BC8F9D383321AACD64C4BD638897A/vdata",
data: {
vrm: p_vrm,
},
success: function(data) {
//Empty the dropdown box first.
$("#p_model").empty();
appendString = "<option value='none'>-- Select your model --</option>";
$.each(data['vehiclemodel'], function (k, v) {
// += concatenate the string
appendString += "<option value='" + k + "'>" + v + "</option>";
});
$("#p_model, #ent_mileage").show();
$('.js-find-my-car').hide();
$('.js-get-price').show();
$("#p_model").append(appendString);
$("#p_model").prop("disabled", false);
$('#skey').val(data['skey']);
},
error: function() {
console.log("We return error!");
}
});
});
The Error function will return an XHR object that you may be able to parse to get the message you want. I don't know what is serving the data so depending on how that's setup your mileage may vary. I've done this using PHP as well as C# and writing to Console, but in both cases I was able to control the returned data.
I used this article : http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/ as a starting point.
You'll need to update:
error: function() {
console.log("We return error!");
}
to
error: function(xhr, status, error) {
console.log("We return error!");
}
Set a break point there in Firebug to check if an XHR object is passed, if not you'll need to find a way to get it.. You mention you can see the JSON in fiddler, it should be available to you. If it is, just use the eval posed in the article and you should be okay. If not you'll have to go and figure out how to get it, depending on your platform difficulty will vary.
A few things to note, eval is messy and can get you into trouble. In the cases I've done this, I removed the eval in production.
Also as of jQuery 1.8 success error and complete are deprecated. Use done fail and always if you plan on updating jQuery in the future.
jQuery API reference, for reference.
http://api.jquery.com/jquery.ajax/

which method of jquery ajax should I use?

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

Ajax - 500 Internal Server Error

I am trying to learn AJAX for this project at work. I have a site that loads medications that a patient is taking.
I call this AJAX function up recursively so that it will append a new table containing a single medication and 7 days worth of history. I am having issues getting the code to execute in FF and IE. Works perfectly fine in chrome. I had alerts displaying the xmlhttp.status and this is what I got:
xmlhttp.status==500 (internal server
error).
I commented out all of my recursion so it is narrowed down to this tid bit of code. ( x keeps track of the number of meds so i know when to stop)
function LoadMeds()
if ( x == MaxMedCount )
{
document.getElementById("the_day").value = parseInt(document.getElementById("the_day").value)+7;
}
if ( x == (MaxMedCount - 1) )
{
document.getElementById("x").value = x + 1;
show();
}
else
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
try
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var div = document.createElement('div');
div.innerHTML= xmlhttp.responseText;
document.getElementById('MedTable').appendChild(div);
document.getElementById("the_med_").value = the_med_;
}
}
catch(e)
{
alert("Error");
}
}
xmlhttp.open("GET","URL with variables passed",true);
xmlhttp.send();
document.getElementById("x").value = x + 1;
}
if more code is needed just let me know.
The 500 (internal server error) means something went wrong on the server's side. It could be several things, but I would start by verifying that the URL and parameters are correct. Also, make sure that whatever handles the request is expecting the request as a GET and not a POST.
One useful way to learn more about what's going on is to use a tool like Fiddler which will let you watch all HTTP requests and responses so you can see exactly what you're sending and the server is responding with.
If you don't have a compelling reason to write your own Ajax code, you would be far better off using a library that handles the Ajax interactions for you. jQuery is one option.
I think your return string data is very long. so the JSON format has been corrupted.
You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
This may be an incorrect parameter to your SOAP call; look at the format of the parameter(s) in the 'data:' json section - this is the payload you are passing over - parameter and data wrapped in JSON format.
Google Chrome's debugging toolbar has some good tools to verify parameters and look at error messages - for example, start with the Console tab and click on the URL which errors or click on the network tab. You will want to view the message's headers, response etc...
Uncomment the following line : [System.Web.Script.Services.ScriptService]
Service will start working fine.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
To allow this Web Service to be called from script, using ASP.NET
AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dep...".
So log on the server and debug from there.
One must use behavior: JsonRequestBehavior.AllowGet in Post Json Return in C#
I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:
Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController#modificarEstado');
and then I put it like this:
Route::get('Mensajes/modificar', 'MensajeriaController#modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');
I had the same error. It turns out that the cause was that the back end method was expecting different json data. In my Ajax call i had something like this:
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"url":"test"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
Now in my WebMethod, inside my C# backend code i had declared my endpoint like this:
public static string PostAjax(AjaxSettings settings)
Where AjaxSettings was declared:
public class AjaxSettings
{
public string url { get; set; }
}
The problem then was that the mapping between my ajax call and my back-end endpoint was not the same. As soon as i changed my ajax call to the following, it all worked well!
var data ='{"url":"test"}';
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"settings":'+data+'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
I had to change the data variable inside the Ajax call in order to match the method signature exactly.

Categories

Resources