I got the error:
request failed: URI too long (longer than 8190)
I've seen other posts on StackOverflow for this one. Those posts recommend:
Not changing Apache settings (agree)
Using post, not get
Not using jsonp with post
I'm using jQuery's AJAX to POST:
$.ajax({
url: "test.php",
dataType: "json",
data: paras,
type: "POST",
success: function(ret){callback(ret);}
});
It's my impression you can use json just not jsonp. Correct? If so, why might I still be getting the error?
You should try setting proccessData to false.
From the docs:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
so to prevent the data being added to the url:
$.ajax({
url: "test.php",
dataType: "application/json",
data: paras,
type: "POST",
proccessData: false, // this is true by default
success: function(ret){callback(ret);}
});
Honestly, I thought this was automatic, but since your url is too long it's worth a shot.
I ran into this issue when using jQuery to submit large forms, and was able to solve it by adding this plugin.
For example, using the following code to submit the form after adding the plugin resolved the issue for me:
$(formSelectorHere).ajaxSubmit({
url: myURL,
type: 'post',
contentType: "multipart/form-data",
data: $(this).serialize(),
success: function(data) {
function(data) {
//success code here//
}
});
If you're not using this to submit a form, this may not be relevant to you and won't solve your problem, but that's the most common situation where this issue appears, so I figured it was worth mentioning. (The plugin should also be able to submit a form using JSON, but haven't personally tested it).
Related
Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
I am trying to make a request to this file : http://traitdesign.com/work/tattva/get.php
this is the code I have so far:
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
}).responseText;
}
getRemote();
well the issue is response headers is empty it doesnt return any results. any help would be appreciated. thank you
Try with JSONP
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
dataType: "jsonp",
});
}
getRemote();
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
Problem is 'Same Origin Policy'. but you can escape from it. but some security issues will remain.
Please check this. http://enable-cors.org/server_php.html
header("Access-Control-Allow-Origin: *");
Include this line into your get.php file.
I think the best in your case would be to write simple ajax action on your server like:
print(file_get_contents('http://traitdesign.com/work/tattva/get.php');
And make ajax call to your new action. It will got through your server so additional server work will be done but you then don't need to care about security policy.
Use JSONP with callback. Also return the value once the call is done.
function getRemote() {
var jqXHR = $.ajax({
type: "GET",
dataType: "jsonp",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
crossDomain: true
});
return jqXHR.responseText;
}
getRemote();
i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.
I'm running into a problem with JQuery Mobile (new to me) and the AJAX-call. I'm using the following code:
$.ajax({
type: "POST",
url: "http://**correct url**/post/todoitem",
beforeSend: addHeaders,
dataType: "json",
contentType: "application/json",
data: { "todoitem":"test" }, // this is just as a test
success: function(result) {
alert("Success: " + JSON.stringify(result));
},
error: function() {
alert("Error: " + JSON.stringify(arguments));
}
});
While executing this, it calls a PHP script where I need the data from the todoitem, so in this case the string "text" (in the end, multiple variables are to be send, but for now I'm just using one parameter for simplicity).
My PHP code looks like this (also just for testing purposes):
echo json_encode($_POST));
The result is: nothing, null. The $_POST seems to be empty. I've searched and tried many things, but most answers (even here on stackoverflow) are about forms and people say I need to serialize the contents of the form. However, I'm not using a form at all.
I also tried
data: JSON.stringify({ "todoitem" : "test" })
as some suggested but this did not work either.
I do know that the data is being transfered because of this little PHP hack I tried:
echo file_get_contents('php://input');
That exactly shows the data: todoitem = test. So where does this all go wrong? I'm working on this for days now! Thnx in advance
The problem is with this part of your code:
contentType: "application/json",`
Removing that line should make the sent Content-Type header default to application/x-www-form-urlencoded and PHP will decode the request into $_POST.
I'm using the $.ajax call to send data to a PHP page:
$.ajax({
type: 'POST',
url: "ajax_more.php",
data: "userid=1"
});
In ajax_more.php I'm trying to read the value of the userid:
$user_id=$_POST['userid'] ;
However, I'm getting an error as PHP doesn't find a value for the index userid.
What am I doing wrong?
UPDATE
I'm sending another ajax variable in the same manner:
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("div#listednotes").append(html);
$("#more"+ID).remove();
}
});
and it is working fine, so using <?php print_r( $_POST ) ?>, the return value is:
Array ( [lastmsg] => 38 ).
You might have used some .htaccess redirection such as removing or adding the "www" to all web requests. Any change on those affects your POST request parameters.
To get this solved, assure you enter your Ajax url as it should be according to your .htaccess rules.
$.ajax({
type: 'POST',
url: "ajax_more.php",
data: {"userid" :1}
});
I cut and pasted your code exactly and it works. So it doesn't look like you are doing anything wrong in the code provided. If you are running other code before checking the $_POST array, that code could be altering its contents or unsetting it.
Your data should be in Key value pairs. and not the way you specified it.
So:
data: "userid=1"
is wrong, should be:
data: {"something" : "value"}