I am trying to pass the value of a textarea to an php page to then be processed and added to a SQL database.
I want the text area to be able to support special characters.
Everything works fine till I put this string in the text area and post it:
JΛ̊KE#2##&($^#%###%))$&#("""
I am getting a 501 Not implemented error.
Now when I paste in certain PHP code into the text area (not to run, purely to save as a string), I get a 403 Forbidden error.
Why does the value of the text area affect the error code?
For now, the paste.php file has no code so that I could try and understand where the error is coming from. I am certain the error is coming from the ajax post. I've looked everywhere online but have not been able to find how to make the string safe to post. encodeURIComponent doesn't seem to work in this case.
Here is the JS for the button press:
var note = $("#note").val();
var dataString = encodeURIComponent(note);
$.ajax({
type: "POST",
url: "php/paste.php",
data: JSON.stringify({
paste: dataString
}),
dataType: 'text',
contentType: "application/json; charset=utf-8",
success: function(msg) {
alert(msg);
console.log(msg)
},
error: function(ts) {
alert(ts.responseText)
}
});
try adding this
Content-Type: application/x-www-form-urlencoded
What was needed was to use this function on the data.
function encode_utf8(s) {
return unescape(encodeURIComponent(s));
}
Change the content type to
ContentType: "application/x-www-form-urlencoded; charset=UTF-8"
and for the kicker, add this to my .htaccess file :
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
Related
I've the below code which I'm using to hit a node.js endpoint. However when it is getting hit, the endpoint URL appends an & to it like this,
http://localhost:3004/expenses/?q=&12/02/2014
Hence I'm not getting the desired result back.
Here is how my code looks like,
$('#myForm').on('submit', (e)=>{
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/?q=',
processData: false,
data: $('#startDate').val(),
contentType: 'application/json',
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
})
})
Can someone shed some light?
The issue is most likely related to the processData: false telling jQuery to not format the data for the request, and the GET url already containing ? in it. Given that you are not giving the request json, I would suggest reducing your call to simplify the issue.
$.ajax({
type: 'GET',
url: 'http://localhost:3004/expenses/',
data: { q: $('#startDate').val() },
success:(data, status)=>{
// alert(status);
},
error:()=>{
alert('problem');
}
});
If you do not give the processData in the options, it will convert the data you give it to a query param for the request. Given that this is a GET request, it will generate the ?q=<value> for you. And as mentioned in the comments, you do not need contentType: application/json on the options as that is telling jQuery to put the content type on the request so the server knows you are sending it json in the body. Which you are not, :)
I'm doing a simple ajax request on a html file to get it's code.
(Actually I don't need the type:"Get", because it doesn't do anything)
jQuery.ajax({
type: "GET",
url: "page-2.html",
dataType: "html",
success: function(response) {
alert(response);
}
});
The response is incomplete. The html file has 400 line sof code but the alert doesn't give me the full file. It is incomplete and stops at line +-130.
It seems that there is some character limitation. Is this possible?
The same happens when I use $.get()
Note: I also get a "Syntax Error -> page-2.html" in the console. Maybe both issues are connected.
jQuery.ajax({
type: "GET",
url: 'page-2.html',
dataType: "html",
success: function(response) {
console.log(response);
alert(response);
}
});
You were missing '' around page-2.html that's why there is error in console.
There is no issue with your ajax request because your script is perfectly working.if you get some error with response means there is some mismatched tag or html format issue that's why u got that error in response.
There is not need to encode URL in single quote ('') or double quote ("") in ajax request with this script.
Please verify your html code in page-2.html.
I have a function defined in my controller:
def get_config_values():
path = unescape(request.vars['path'])
config = get_config_as_dict(path)
return dict(config)
And in my view I use jQuery $.ajax() to call it in the view:
$.ajax({
url: "{{=URL('get_config_values.json')}}",
contentType: "application/json; charset=utf-8",
data: {
path: page_path,
},
error: function(x, y, z) {
show_error(x.responseText, y, z);
hide_drawer();
},
success: function(data) {
$('#drawer_content').html(data);
},
type: 'POST',
});
And put simply I cannot get this to work.
if I use type: 'POST' then the function is called as expected but the path parameter never makes it through to the controller function (it is just None)
if I change it to type: 'GET' web2py decides the function does not exist at all and returns a HTTP 404 (and this remains even if I remove .json from the URL). No errors in the web2py error log.
Web2py seems to behave quite strangely here - to get the POST working in the first place I had to explictly set contentType: "application/json" otherwise I'd see a 404 there as well, despite the data:'json' already there.
Has anyone else seen and worked around this behaviour? I don't care if the call is GET or POST, I just want it to work!
There are a few problems. First, when a web2py action returns a dictionary, web2py looks for an associated view to execute (based on the path of the action as well as the extension). In this case, it will look for a view with the path /views/controller_name/get_config_values.json. If it doesn't find that view, it may attempt to use the generic.json view, but only if you have explicitly enabled the generic view via response.generic_patterns (in the scaffolding app, all generic views are enabled by default, but only for local requests). Otherwise, you will get a 404 error (if you inspect the body of the error message in the browser developer tools, you should see a message about an invalid view).
Second, to post JSON via jQuery, you have to convert your Javascript object to a JSON string:
data: JSON.stringify(
{
path: page_path
}
),
With the above, you should now have the value of page_path in request.vars.path on the server.
Finally, if you request a .json URL from web2py, it will set the Content-Type response header to "application/json". However, based on your Javascript code, it appears you want to return HTML (given that you are placing the results into a div on the page). So, you should probably not use the .json extension in the request (you can also explicitly tell jQuery that the response is HTML by setting dataType: 'html').
So, try the following:
$.ajax({
url: "{{=URL('get_config_values')}}",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
path: page_path,
}),
error: function(x, y, z) {
show_error(x.responseText, y, z);
hide_drawer();
},
success: function(data) {
$('#drawer_content').html(data);
},
type: 'POST',
});
Then either create a get_config_values.html view that generates the desired HTML from the returned dictionary, or otherwise have the get_config_values function directly return an HTML string.
If you instead do want to return JSON to the browser, then you will need to change your success callback to process the JSON before attempting to place it in a div.
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.
I am using ckeditor to format some data inside my textarea
<textarea id="editorAbout" rows="70" cols="80" name="editorAbout"></textarea>
Now when i try to post this data using jQuery.ajax like this,
var about=escape( $("#editorAbout").text());
$.ajax({
type: "POST",
url: "../Allcammand.aspx?cmd=EditAboutCompany&about="+about,
type:"post",
async: false ,
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); }
});
I get the error
HTTP Error 414. The request URL is too long.
I am getting the error here: http://iranfairco.com/example/errorLongUrl.aspx
Try clicking on the Edit Text button at the bottom left of that page.
Why is this happening? How can I solve it?
According to this question the maximum practical length of a URL is 2000 characters. This isn't going to be able to hold a massive Wikipedia article like you're trying to send.
Instead of putting the data on the URL you should be putting it in the body of a POST request. You need to add a data value to the object you're passing to the ajax function call. Like this:
function editAbout(){
var about=escape( $("#editorAbout").text());
$.ajax({
url: "Allcammand.aspx?cmd=EditAboutCompany&idCompany="+getParam("idCompany"),
type:"post",
async: false,
data: {
about: about
},
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); ShowMessage("??? ?? ?????? ??????? ????","fail");}
});
}
For me, changing type:"get" to type:"post" worked, as get reveals all queries and hence make it bigger url.
Just change type from get to post.
This should help. :)
In my case, there was a run-time error just before the post call. Fixing it resolved the problem.
The run-time error was trying to read $('#example').val() where $('#example') element does not exist (i.e. undefined).
I'm sure this will, certainly, help someone.
In my case, the error was raised even though I was using 'POST' and the call to the server was successful. It turned to be that I was missing the dataType attribute...strange but now it works
return $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
A bit late to the party, but I got this 414, while using POST. It turned out is was a max path length in windows causing this error. I was uploading a file, and the actual request length was just fine (using post). But when trying to save the file, it exceeded the default 260 char limit in windows. This then resulted in the 414, which seems odd. I would just expect a 501. I would think 414 is about the request, and not the server handling.