I am trying to send an XML file from a textfield in my html, via ajax to a PHP file. This is the almighty PHP file:
<?php
$data = urldecode($_POST["xml"]);
echo $data;
?>
Data is sent to this file as such:
$("#btn_save").click(function() {
var data = escape($("#textfield").text());
alert(data);
$.ajax({
url: "validate.php",
method: "POST",
data: "xml=" + data,
complete: function(e) { alert(e.responseText); }
});
});
Now, as long as I don't sent more than a few lines of code, it works as it should. When I paste in a 60 line XML file however, validate.php returns
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /xml_stylist/form/validate.php
on this server.</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache mod_fcgid/2.3.5 mod_auth_passthrough/2.1 mod_bwlimited/1.4 FrontPage/5.0.2.2635 Server at dahwan.info Port 80</address>
</body></html>
What am I doing wrong?
Thanks
Change
method: "POST"
to
type: "POST"
that may do the trick.
BenSho is correct, the argument is called type. In addition:
$("#textfield").text()
I'm guessing that's a <textarea>. You shouldn't use text() or html() to read content from an input field, it doesn't do what you think. Use val().
var data = escape($("#textfield").text());
Don't ever use escape(). It is a weirdo JavaScript-specific function that looks like URL-encoding but isn't. If you use it for URL-encoding you will corrupt plus signs and all non-ASCII characters.
The correct JavaScript function for URL-encoding is encodeURIComponent(). However, since you are using jQuery, much better to let it work out URL-encoding for you by passing an object in:
data: {xml: $("#textfield").text()},
Finally:
$data = urldecode($_POST["xml"]);
You don't have to (and shouldn't) URL-decode anything manually. PHP URL-decodes parameters in a request body into raw strings for you.
Most browsers have a practical maximum of 2,083 characters in the url; there is no limit for a POST request. A GET request will pass the parameters in the url whereas a post does not. It all depends on how much you're actually sending to determine which you should use or if you're sending sensitive data (use POST).
Setting the data option on ajax calls means jquery will add these to the query string in a GET request. Most browsers have a limit on the length of a get request. If your xml data is too big, you should switch to POST.
Optimize your php.ini
post_max_size you may have to set
your memory_limit to higher value..
depends on the memory usage of your
script also
max_execution_time could be a
problem
try this:
$("#btn_save").click(function() {
var data = $("#textfield").text();
$.ajax({
url: "validate.php",
type: "POST",
data: {"xml": data},
complete: function(e) { alert(e.responseText); }
});
});
Related
I'm reading a .CSV (excel) file using javascript, when I console.out the .CSV data I get it in this format:
http://prntscr.com/ivdn1h
I have to import this data in my database. I use ajax to send the data via POST request to my REST endpoint, where I call the function that does the import.
AJAX CODE:
function pushToDatabase(lines){
var array = lines;
$.blockUI();
$.ajax({
url: "rest/v1/upload",
method: "POST",
dataType: "json",
data: {
file: array
},
success: function() {
alert("Data has been uploaded succesfully.");
}
});
$.unblockUI();
}
ENDPOINT (flightPHP):
Flight::route('POST /upload', function () {
$file = Flight::request()->data->file;
$status = Flight::pm()->upload_records($file);
Flight::json($status);
});
But when I send the request, I get this response:
<b>Warning</b>: Unknown: Input variables exceeded 1000. To increase the limit change max_input_vars in php.ini. in <b>Unknown</b> on line <b>0</b><br />
Here is the http request header:
http://prntscr.com/ivdrmz
I'm not interested in changing my max_input_vars. I hope somebody can help me to fix my data format.
Thanks in advance. :)
Check if, changing datatype: "text/plain" in your ajax call, solves your problem.
However, as Niels, suggested in his post, you should actually convert your data to a JSON and then post as single string variable
To summarise, it is the Content-Type sent by header set for JSON. You are trying to send FormData and not Json to php file.
I spent a whole day to discover the solution for a similar issue.
I am using WAMP 3.0.8 PHP 7.0.10 Apache 2.4.23 and trying to build my first JSON API.
The ajax call does send the data to the server. I can see it stored in the text file.
My AJAX looks like this.
$(document).ready(function(){
$('#order').click(function(){
var send = {"name":"Jo Moe", "age":39, "city":"Meridian"};
var prescription = JSON.stringify(send);
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'https://apa.superserver.com/receive.php',
data: {"scripts": prescription},
success: function(data){
console.log(data);
alert(data);
$('#success').html('<p>Finished</p>');
}
});
});
});
Server side looks like this:
if(isset($_POST["scripts"]) && !empty($_POST["scripts"])){
$sent = filter_input(INPUT_POST, "scripts", FILTER_SANITIZE_SPECIAL_CHARS);
$scripts = html_entity_decode($sent);
file_put_contents("jsonScript.txt", $scripts);
$finish = "Message Received!";
echo json_encode($finish);
}
Now this all worked when it was on the same server. When I separated the receive.php and put it on the remote server. It no longer shows the response.
Thanks!
UPDATE:
Get json ajax php form to work remotely
The link above fixed my issue and gave me more information in the console to figure out what was happening. (I should not have been given a -1) The problem with searching the index here that if you don't use the exact terms in the post it is nearly impossible to find. (my two cents)
Adding the error function and changing from "data" to "response" made the difference along with the xhr. I can see everything.
This my return to the console:
Object {readyState: 4, responseText: "↵↵hello!"Message Received!"", status: 200, statusText: "OK"}
ajax.php:56 parsererror
ajax.php:57 SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at parseJSON (jquery-1.6.4.min.js:2)
at b$ (jquery-1.6.4.min.js:2)
at w (jquery-1.6.4.min.js:4)
at XMLHttpRequest.d (jquery-1.6.4.min.js:4)
As you can see the response text is what the server is sending back.
I did have to modify my httpd.conf to turn on the mod_headers.c and added an .htaccess .
UPDATE 2:
Figured out what was causing the parse error. I had a print "hello!" line in my server side file that I had there for other troubleshooting. Once I removed it and had only the posted server side code. Everything is peachy now. Onward!!
If I understand correctly You want to make ajax request to another domain. It's blocked because of Same origin policy. To achieve your goal You can implement JSONP
I am using this ajax code to send data to server:
$.ajax({
data: postData,
type: method,
url: url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
error: function(jqXHR,textStatus,err){alert("Error returned from ajax call "+err);},
success: function(data,status,jqXHR){
// process response...
}
});
postData is a query string with many values while method is GET or POST
The problem is that, when I send a query string that contains a value like Älypuhelimen lisävarusteet, the result in database is �lypuhelimen lis�varusteet
The database connection collation is utf-8, and this works fine when I do not use ajax to post and save to database... It is definitely ajax that messes up the encoding...
I have also tried using encodeURIComponent() function on the data, and it becomes %C4lypuhelimen%20lis%E4varusteet if I use it... same goes for escape() function...
any help will be appreciated...
You should try jQuery Base64 encode.
JavaScript:
<script src="jquery.min.js"></script>
<script src="jquery.base64.min.js"></script>
<script>
enctext = $.base64.encode("yourtext");
//your ajax code goes here.
</script>
PHP :
<?php
$org_text = base64_decode($_POST['your_variable']);
?>
jQuery Base64 plugin.
download from here.
https://github.com/carlo/jquery-base64
Try changing the column in the database to utf16_bin Collation
Post you php database connection code.
Just for information and to help others that might fall in the same situation...
The problem was with the postData itself... it was parsed such that every post variable was applied with escape()... Using encodeURIComponent() instead of escape() worked!
Summary:
Donot use escape() function to url-escape query components... use encodeURIComponent() instead...
I just started to work on calls to a php file which is present in a different server. I am aware of CORS which is essential for cross domain requests. I have been trying to call this file through ajax methods refering to other websites and tutorials and I have seen discussions to find a solution but they are not working for me. Please help.
here is my calling method:
$.ajax({
type: "GET",
url: "http://cs-server.usc.edu:27952/ResponseProg.php?callback=?", //Relative or absolute path to response.php file
datatype: "jsonp",
data: dataInput,
jsonp:'jsoncallback',
crossDomain:true,
success: function(data)
{
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found")
{
var paginate=setPager(0);
$("#pgn").html(paginate);
}
},
error: function() {
$("#rtrn").html("Data not retrieved successfully");
}
});
Here is my PHP code snippet:
<?php
#code for data processing...
$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES);
echo $_GET['jsoncallback']."(".$rsltjson.");";
?>
I am trying to accomplish this by using JSONP. Should I have any headers?
Are there any errors in my code?....How can I accomplish this? dataInput is the serialized form of form data
The CORS way
You need to put the appropriate header in your php script and output only the JSON:
<?php
header('Access-Control-Allow-Origin: *');
// rest of the code
// output JSON only
echo $rsltjson;
?>
Then using a XMLHttpRequest/ajax call should retrieve the data just fine as JSON without resorting to JSONP.
Mozilla has plenty to read about it
The JSONP way
Since the whole point of JSONP is to bypass cross-domain restrictions, calling a JSONP resource with XMLHttpRequest/ajax, a method in which cross-domain security is fully applied (presumably), is completely useless.
JSONP works by injecting code directly into your page, calling a function that you defined, which is why a JSONP url takes an argument. Therefore, the correct way to call your JSONP url is this:
<script>
function myDataFunc(data) {
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found") {
var paginate=setPager(0);
$("#pgn").html(paginate);
}
}
</script>
<script src="http://cs-server.usc.edu:27952/ResponseProg.php?jsoncallback=myDataFunc"></script>
The JSONP url will return something that looks like this:
myDataFunc({"a":"fhsfg","b":"qfdgers","c":"difgij"});
Since it is included as a script, it will be executed directly in your page, calling the function myDataFunc() that you defined earlier.
Also note that your php file use the GET parameter jsoncallback while your javascript calls the url with the parameter callback, which would not work.
Finally, you use jQuery.parseJSON(), which produces this error from your code:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The reason can be found in the jQuery docs:
jQuery.parseJSON( json )
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown.
Your php script feeds your callback with a JSON object
{"a":"fhsfg","b":"qfdgers","c":"difgij"}
rather than a string representing a JSON object
'{"a":"fhsfg","b":"qfdgers","c":"difgij"}'
Note the surrounding quotes, which makes this data a string. We fix this in php by adding the quotes around the data:
echo $_GET['jsoncallback']."('".$rsltjson."');";
Obviously if your JSON data contains single quotes, you will have to escape them.
This is really bizarre. I am trying to submit data to the server and have a PHP script parse the data and then send back a response. A correctly formed URL is being sent:
http://localhost/ajax/test.html?row=rec_no_1
, but the server does not seem to respond with content from the PHP script despite a return code of 200. In fact, Developer Tools (in Google Chrome) doesn't say anything about the PHP file. The AJAX "data" statement must be formatted properly otherwise I wouldn't get the correct URL. POST (instead of GET) doesn't help.
If I change the AJAX data to a string, then it works fine. This implies there is something wrong with the AJAX data. But I can't understand what given that the URL is correctly formed and does change depending on which row I select.
Any ideas?
Here is the Javascript:
$(document).ready(function() {
$(".submit").click(function() {
$.ajax({
type: 'GET',
url: 'getTable.php',
dataType: 'html',
data: {row: $('input[type='checkbox']:checked').val()},
//data: {row: 'rec_no_2'},
success: function($result) {
$('.tableHolder').text($result);
}
});
return false;
});
});
Here is the PHP code:
<?php
if (isset($_GET['row'])) {
$tableRow = $_GET['row'];
echo $tableRow;
}
else
echo 'TEST';
?>
Your syntax is incorrect:
$('input[type='checkbox']:checked').val()
You should use double quotes around checkbox:
$('input[type="checkbox"]:checked').val()
Anyway do a console.log( $('input[type="checkbox"]:checked').val() ) before the ajax call just to find out which value is being sent.
Try moving your javascript file to server. Ajax don't work on cross domain. You are running the javascript file on localhost and trying to fetch information from live server. Keep both php and javascript file on same server, either live or localhost. It will work fine.
One more thing, try changing the url parameter of your ajax request. try complete url or try putting or not putting a slash / before your filename.