ajax submit wrong data to PHP - javascript

This is html file that submit ajax by button click to PHP script(on IIS).
But PHP script received wrong formatted data (there are brackets added [] and no parameter 'section' transmitted
What can be wrong
It would be good to have solution both: in JQuery and pure javascript
------------------- HTML
<!DOCTYPE html>
<html STYLE="height:100%;">
<head></head>
<body>
<SCRIPT>
function zPostToTopic_ajax(){
var url='http://the_server/infospace/php/infospace2.php';
var formData2 = new FormData();
formData2.append('section', 'general');
formData2.append('action2', 'preview');
http_request=new XMLHttpRequest();//work for IE11 too, // code for IE7+, Firefox, Chrome, Opera, Safari
http_request.open("POST", url);
//------------------------------------
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200)
alert(http_request.responseText)
}
http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
http_request.send(formData2);
}
</SCRIPT>
<FORM NAME=form_post_to_topic ID=form_post_to_topic METHOD=POST action="http://the_server/infospace/php/infospace2.php">
&nbsp <INPUT TYPE=BUTTON VALUE=Send onClick="zPostToTopic_ajax();return false;">
</FORM>
</body>
</html>
-------------------------- PHP script
<?php
print_r($_REQUEST);
?>
--------------------------- Received data:
Array
(
[-----------------------------276402058428
Content-Disposition:_form-data;_name] => "section"
general
-----------------------------276402058428
Content-Disposition: form-data; name="action2"
preview
-----------------------------276402058428--
)

Use jQuery's .ajax() function. Here's an example where I post a file upload too.
var jform = new FormData();
jform.append('supply_id',supply_id);
jform.append('fuel_usage',$('#fuel_usage').val());
jform.append('cost',$('#cost').val());
jform.append('currency',$('#currency').val());
jform.append('evidence',$('#evidence').get(0).files[0]);
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: jform,
dataType: 'json',
contentType: false,
cache: false,
processData: false,
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});

Your problem is that you are setting the wrong content type for your request. When you use a formdata object the content type will be multi-part/formdata.
So when you are using a formdata object you do not set the content type and it is set for you.
function zPostToTopic_ajax(){
var url='http://the_server/infospace/php/infospace2.php';
var formData2 = new FormData();
formData2.append('section', 'general');
formData2.append('action2', 'preview');
http_request=new XMLHttpRequest();//work for IE11 too, // code for IE7+, Firefox, Chrome, Opera, Safari
http_request.open("POST", url);
//------------------------------------
http_request.onreadystatechange = function() {
if(http_request.readyState == 4 && http_request.status == 200)
alert(http_request.responseText)
}
http_request.send(formData2);
}

Related

Convert Ajax submit form then get HTML response to Pure Javascript

//THIS AJAX CODE WORKING GREAT.
$(document).ready(function(e) {
$("#ajaxupload").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "http://example.com/upload",
type: "POST",
data: new FormData(this),
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data){
//if success. Response is HTML. data = html. insert to my .result-wrapper.
$(".result-wrapper").prepend(data);
},
error: function(){
console.log('there\'s error!')
}
});
}));
});
How to convert this Ajax Jquery to pure Javascript? I've try to find solution around Stackoverflow then try to implement codes by answer was mark as accepted still error, my backend Controller not detect the data input value..
With ajax codes above.
1. Sumbit and get response without refresh the page.
Response is HTML.
No need to set data. because data already set in my HTML form.
Form have multiple input file upload and multiple input name. So length of input not a static number, depend files.
How to implement it with javascript? Submit without refresh, get response, then possible to submit data filled in HTML dinamically?
I've try do that with code below.
document.getElementById('ajaxupload').addEventListener('submit', function(e) {
e.preventDefault();
//e.submit();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/upload/', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
//xhr.send();
xhr.send(document.getElementById('ajaxupload').innerHTML); //my form id = ajaxupload
});
HTML:
<form action="http://example.com/upload" id="ajaxupload" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input id="insert-file" name="usr_files[]" type="file" multiple="">
<!--other input will generate inside this form on change `insert-file` .. depend on how many length file selected. ex if 2 files selected:
<input class="custom-file-name" name="usr_files[text][0]" type="text" value="My custom file name" required/>
<input class="custom-file-name" name="usr_files[text][1]" type="text" value="My custom file name no.2" required/> -->
</form>
Use the same formdata object in the native code
document.getElementById('ajaxupload').addEventListener('submit', function(e) {
e.preventDefault();
var formData = new FormData(this);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://example.com/upload/');
xhr.onreadystatechange = function() {
if ( xhr.readyState === 4 && xhr.status === 200 ) {
console.log( xhr.responseText );
}
}
xhr.send( formData ); //my form id = ajaxupload
});
function ajaxGet(url, cb, token){
      var ajaxReq = new XMLHttpRequest();
      ajaxReq.addEventListener('load', function(){
        if(ajaxReq.status === 200) cb(null, {responseText: ajaxReq.responseText, rawAjaxRequest: ajaxReq});
        else cb({statusCode: ajaxReq.status, rawAjaxRequest: ajaxReq}, null);
      });
      ajaxReq.addEventListener('error', function(data){
        console.dir(data);
        var err = new Error('A fatal error occurred during ajaxGet, see console for more information');
        err.name = 'XMLHttpRequestError';
        cb(err, null);
      });
      ajaxReq.open('GET', url, true);
      if(token){
        ajaxReq.setRequestHeader('Authorization', token);
      }
      ajaxReq.send();
    },

FormData not appending the data

I am just scratching my head, and do not understand, what happens here. This code has worked both in production and in my developer environment.
Here is the reference, I do exactly the same.
var fileToUpload = $('#productsFile').prop('files')[0];
var formData = new FormData();
formData.append('file', fileToUpload);
formData.append('action', 'csvUpload');
formData.append('siteId', $('#siteId').val());
console.log($('#siteId').val());
console.log(fileToUpload);
console.log(formData);
The output in the console:
10
File { name: "H00447.PriceList.csv", lastModified: 1464960003935, lastModifiedDate: Date 2016-06-03T13:20:03.935Z, size: 14859917, type: "application/vnd.ms-excel" }
FormData { }
Object has created, the values are fine, so what could be the problem here? Tested with Firefox Developer Edition.
EDIT
Here is the code to send the data to the ajax:
$.ajax({
url: ajaxUrl, // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post'
}).done(function (msg) {
if (parseInt(msg) !== 0) {
alert(msg);
} else {
location.reload();
}
}).fail(function (msg) {
alert('Error: ' + msg.statusText);
});
In the ajax.php I just var_dump($_REQUEST); and shows me an empty array.
EDIT2
I tried it on another localhost environment, I've just added some random keys and values, and everything was fine, even in FF and Chrome.
So I came back to this issue, and just commented out the fileToUpload section.
The other two value was in the $_POST. If I add the file, the $_POST will be empty.
Something wrong with the file.
EDIT3
No I just tested it with a small file, what is about 3-4Kb, and everything is fine. My production file is 14Mb, I think that will be the problem.
SOLUTION
This whole thing because of the filesize. I incrased the post limit, and max file size in php.ini and viola. Things are works. Thank you for your help.
Try this to log keys and values:
formData.forEach(function (value, key) {
console.log(key, value);
});
The data is send but you need to use POST not GET:
var formData = new FormData();
formData.append('action', 'csvUpload');
var xhr = new XMLHttpRequest();
xhr.open("POST", "ajax.php", true);
xhr.send(formData);

Different behavior for empty XML response between IE and Firefox

I'm using jQuery to read an XML file. Sometimes the XML is empty, and I expect the error function (no_info) is executed because the file is not formatted according to the dataType.
In IE 10 the Error function is executed. But in Firefox (40.0.2) the success function (parse) is executed. Why both browsers behave differently and which one is correct?
$.ajax({
url: '/~play/shout.xml',
dataType: "xml",
success: parse,
error: no_info
});
Looks like there's a bug in IE
how about you handle it yourself?
function parseXml(xml) {
if ($.browser.msie) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XML_file.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xml = xmlDoc;
}
return xml;
}
previous answer
which JQuery version do you use? I use the most actual and with my ajax function I couldn't encounter any issues. That's my code
function sync(arg, callback){ //ajax result
$('.loader').show();
$.ajax({
method: 'GET',
url: 'liveSearch.php',
data: arg, // send argument and update
success: function(data, status, xhr){
$('.loader').hide();
callback(data);
},
error: function(xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
}
function onCallback(data) {
result = data;
}
dataType parameter merely indicates what "Content-Type" header you are expecting.
As long as the file exists and served with a valid Content-Type Success function should be triggered.
instead of just /~ try passing the whole URL from which you want to retrieve the XML file.

Upload photo in background with ajax

So I'm a bit new to ajax, I just want to see if anyone can help me with this...
I have my main page. I'll just put the element I'm working with so I don't have to put the whole page.
<input type="file" id="myphoto" />
Then, instead of submitting it, what I want to do is run it through a javascript function with an ajax form in it like this
$.ajax({
type: "POST",
url: "myphppage.php",
"Whatever other code needed"
})
to upload the photo. Then, the form URL could be a php page that moves the photo to a different directory. I hope you know what I mean. Any help would be greatly appreciated...
first make a html file which select the file from anywhere, like
uplaod.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX UPLOAD</title>
</head>
<body>
<form enctype="multipart/form-data">
<input id="file" type="file" />
<input type="button" id="upload" value="Upload" />
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="upload.js"></script>
</html>
now, make js file like below,
upload.js
$(document).ready(function() {
$('#upload').on('click', function() {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
alert(data);
}
});
});
});
now, make a directory uploads and a php file which upload the file to upload directory
upload.php
<?php
if (0 < $_FILES['file']['error']) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
echo "success";
}
XHR2 AJAX request can submit binary data like images:
DEMO
However, changing the address bar (windows.location) will interrupt the upload as the new page is loaded. You can work around of this by loading pages via AJAX and using History API:
Demo1
Those who have the common sense and/or enough brain to avoid gayQuery...
function uploadFile(){
var form_data = new FormData();
var first_file = document.getElementById('your_input_element_which_type_is_file').files[0];
var link = 'file_upload.php'; /*or which ever you have, maybe add ?params=xxx&other_params=yyyy */
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var response = xmlhttp.responseText;
/* check your custom response here */
}
/* check other errors here too */
}
form_data.append('file', first_file);
xmlhttp.open('POST', link, true);
xmlhttp.send(form_data);
}

How to pass AJAX variables to PHP

I understand I can't pass AJAX Vars directly to PHP, being a client versus server side script. But that being said, here's my code:
setInterval(function()
{
//do something after you receive the result
var xmlhttp;
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()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("message_area").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","messages.txt",true);
xmlhttp.send();
}
I know I can indirectly process AJAX variables by POSTing them to a PHP page using AJAX, like so:
$.ajax (
{
type: "POST",
url: "decode.php",
});
I just need to know how to pass the contents of the "messages.txt" file used in the xmthttp.open call to a PHP file for further processing.
How can I do this?
If you are using pure javascript:
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
or if you're using jquery, simply:
$.ajax (
{
type: "POST",
url: "decode.php",
params: {param1: "val1", param2: "val2"}
});
Hope this helps :
$.get( "messages.txt", function( data ) { //Fetching contents of messages.txt file.
$.ajax ({
type: "POST",
url: "decode.php",
data: data, //passing contents of messages.txt file to decode.php
success: function(result){
alert(result);//Getting result from decode.php
}
});
});
cheers
Are you using jquery? You first code block is regular js, the second is jQuery's ajax short hand.
That said, if you want to POST data with ajax using jQuery, you would do something like the following.
var PostData = "something";
$.ajax({
type: "POST",
url: "someurl",
data: PostData
}).done(function(returnData) {
//process data returned from server, if there is any
});

Categories

Resources