XHR Request with FormData is POSTing an empty array, - php

I am working on my own version of this.
Everything works, except the POSTed values are empty. var_dump on the PHP side shows an empty array. What's wrong?
function readfiles(files)
{
console.log('Reading Files...');
console.log(files);
console.log("There are " + files.length + " elements to this array.");
var formData = new FormData();
formData.append('file', files[0]);
console.log(formData);
console.log("Posting XHR request...");
// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/devnull.php',false);
console.log("sending data...");
console.log(formData);
xhr.send(formData);
}
$(document).ready(function(e) {
$("#holder").on('dragenter',function(e) {
e.preventDefault();
$(this).addClass('hover');
});
$("#holder").on('dragleave',function(e) {
e.preventDefault();
$(this).removeClass('hover');
});
$("#holder").on('dragover',function(e) {
e.preventDefault();
if(!($("#holder").hasClass('hover')))
$("#holder").addClass('hover');
});
$("#holder").on('drop',function(e) {
e.preventDefault();
console.log(e.originalEvent.dataTransfer.files);
$(this).removeClass('hover');
readfiles(e.originalEvent.dataTransfer.files)
return false;
});
});
Firebug tells me that there is an element in the array:
FileList { 0=File, length=1, item=item(), more...}
But after we append it to the FormData object, I get this:
FormData { append=append()}
And the final var_dump on the PHP side says this:
<pre>array(0) {
}
</pre>

use this code to dispaly file data
<?php var_dump($_FILES);?>

Related

How to rewrite Ajax without using JQuery for my code

Hi I am currently trying to save an image on my canvas to my database, but my code uses jQuery of which I am not allowed to. Can someone please help me with an equivalent of this ajax command without using JQuery, here is my code:
document.getElementById('save').addEventListener('click', function()
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL("image/png");
$.ajax(
{
type: "POST",
url: "../webcam/save_image.php",
data: {image: dataUrl}
})
.done(function(respond){console.log("done: "+respond);})
.fail(function(respond){console.log("fail");})
.always(function(respond){console.log("always");})
});
You can use Native XMLHttpRequest Objects to accomplish this. I believe your code should look something like this, I haven't tested it though, so you will need to tweak it somewhat I'm sure.
document.getElementById('save').addEventListener('click', function()
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL("image/png"), xhr = new XMLHttpRequest();
xhr.open('POST', '../webcam/save_image.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText !== dataUrl) {
console.log('fail');
}
else if (xhr.status !== 200) {
console.log('fail');
}
};
xhr.send(encodeURI('url=' + dataUrl);
Reference: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting

Calling jQuery in Ajax response

I want to call a jQuery function that acts upon a form in AJAX response.
How do I do it???
jQuery Function
$(document).ready(function (e) {
$("#load_timetable").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "load_timetable.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#time_table").html(data);
},
error: function() {}
});
});
});
Another AJAX Function
$(document).on("click", ".open-viewFacultyDialog", function () {
var uid = $(this).data('id');
$('#update').click(function() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) {
**//I would like to call JQUERY here**
document.getElementById("update_action_response").innerHTML = "";
var ajaxDisplay = document.getElementById('update_action_response');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var dept_slot = document.getElementById('dept_slot').value;
var subject = document.getElementById('subject').value;
var faculty1 = document.getElementById('faculty1').value;
var faculty2 = document.getElementById('faculty2').value;
var faculty3 = document.getElementById('faculty3').value;
var queryString="?id="+uid+"&dept_slot="+dept_slot+"&subject="+subject+"&faculty1="+faculty1+"&faculty2="+faculty2+"&faculty3="+faculty3;
ajaxRequest.open("GET", "update_timetable.php"+queryString, true);
ajaxRequest.send(null);
});
});
In simple I would like to reload the contents after updation without page reload by submitting the same parameters that are used to load the contents before update.
Use Promise method which is already defined in jquery.you can use it if data transfer successfully. such that if promise returns true then perform this task.else other task.

Ajax - multiple validation

I have set up some ajax code to validate multiple fields inside a form using php. The code works like a charm, but I wanna minimize the javascript used.
As you can see at the code below, Im getting the getElements('input') ... that validates all input fields and then getElements('textarea') that validates... ya u know! ;o) Textarea is the last line in the code below and the javascript after that is the same as inpt
I'm validating the input, textarea, selection list, checkbox, etc. in my controller using php, but the code after getting the elements is the EXACT SAME.
So I was thinking that I might could make a switch case or if else with javascript to loop the elements and only write the duplicated javascript once....
Could that be done?
window.addEvent('domready', function(){
$('container').getElements('input').addEvent('keyup', function(e){
//stop the input-tag event
e = new Event(e).stop();
//identify which item was activated
var querystring = this.title;
var value = this.value;
var myXHR = new XHR({
method: 'get',
onSuccess: function(e){
var myString = myXHR.response.text;
var myStringArray = myString.split("###RAWR###");
$(myStringArray[1]).innerHTML = '<em class="checking"> </em>';
setTimeout( ajax , 3500 );
function ajax(){
$(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
}
}
});
myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
});
$('container').getElements('textarea').addEvent('keyup', function(e){
You can put the tagnames in an array loop it and call a function with your validation.
window.addEvent('domready', function(){
var tagNames = ["input", "textarea", "select"];
for (var i = 0; i < tagNames.length; i++)
{
validate(tagNames[i]);
}
});
function validate(tag)
{
$('container').getElements(tag).addEvent('keyup', function(e){
//stop the input-tag event
e = new Event(e).stop();
//identify which item was activated
var querystring = this.title;
var value = this.value;
var myXHR = new XHR({
method: 'get',
onSuccess: function(e){
var myString = myXHR.response.text;
var myStringArray = myString.split("###RAWR###");
$(myStringArray[1]).innerHTML = '<em class="checking"> </em>';
setTimeout( ajax , 3500 );
function ajax(){
$(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
}
}
});
myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
});
}

$_REQUEST var is empty from post send

I'm doing a ajax function for wp. But i get always the response 0. I see the code of the file admin-ajax.php and see this:
if ( empty( $_REQUEST['action'] ) )
die( '0' );
This is my js function ajax.
function fnc(){
var ajax=new XMLHttpRequest();
ajax.open("POST", "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php");
ajax.onreadystatechange= function(){
if (ajax.readyState === 4) {
if (ajax.status === 200) {
alert(ajax.responseType);
alert(ajax.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
ajax.send("action=some_function");
}
In order to have the send string be used as form data, you will probably need to add the following header:
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Without this, PHP will not turn the raw POST data into $_POST/$_REQUEST variables.
$.ajax({
type:'POST',
url:"<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
data:'', // what you want to post
success:function(data){
alert(data);
});
}
});
}
try this
If you want to use javascript and XMLHttpRequest this is the full way to do that :)
function ajax_post(){
// Create our XMLHttpRequest object
var ajax=new XMLHttpRequest();
// Create data to send to our PHP file
var url = "xyz.php";
var fn = document.getElementById("a").value;
var ln = document.getElementById("b").value;
var variable = fn+" hello "+ln;
hr.open("POST", url, true);
// Set content type header for sending url encoded variables
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Get the onreadystatechange event for the XMLHttpRequest
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
var return_data = ajax.responseText;
alert(ajax.return_data);
// Send the data to PHP now... and wait for response to update the status div
ajax.send(variable); // Actually execute the request
}
}
}

Document.ready() function

This is my ajax function
<script language="JavaScript" type="text/javascript">
var num = 1;
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (++num)); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
Now i have this too find the correct div/class to run the ajax function in:
$('.eventcontainer.button').click(function() {
$.post('javas.php', function(data) {
$(this).parent('div').find('.status').html(data);
})
});
However im not sure where to implement this in my code
It's not a good idea to write your own ajax-request if you want to run your code on multiple browsers. If you have jQuery on your hand and you want a post ajax-request use the jQuery function:
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
example for document ready to use:
function fooBar() {
//some code
}
$(document).ready(function(){
// all your jquery in here
$('body').hide().fadeIn(2000);
// or call your own functions
fooBar();
});
You can use this:
$(function(){
$('.eventcontainer.button').click(function() {
$.post('javas.php', function(data) {
$(this).parent('div').find('.status').html(data);
})
});
})

Categories