$_POST is null from ajax req - php

so I'm trying to upload files via a form sent using AJAX, except $_POST returns an empty array (so does $_FILES) - though I'm not sure why. Here is the top of my form:
HTML - generated from PHP (inside WP function)
$html .= '<form method="post" class="form-horizontal" id="product-slides-form" enctype="multipart/form-data">';
AJAX
//edit product gallery
$('#update-product-gallery').on('click', function()
{
var product_id = $(this).data('id'),
slides_form = $('#product-slides-form'),
slides_form_data = new FormData(slides_form[0]);
//create array of slides
var slides = {},
counter = 0;
$.each(slides_form.find('input'), function(j, v)
{
if ($(this)[0].files) {
$.each($(this)[0].files, function(i, files)
{
slides_form_data.append('slides-'+ counter, files);
counter++;
})
}
});
//add slideshow data
slides_form_data.append('slides', JSON.stringify(slides));
slides_form_data.append('product-id', product_id);
var slides_data = {};
slides_data['product_id'] = product_id;
slides_form_data.forEach(function(val, key)
{
slides_data[key] = val
});
//if I change data: to below test FormData than it works
var test = new FormData();
test.append('me', 1);
$.ajax({
data: slides_data,
dataType: 'text',
type: 'post',
url: PLUGIN_ROOT+ 'admin/inc/scripts/add-product-slides.php',
cache: false,
contentType: false,
processData: false,
success: function(res) {console.log(res)},
error: function(res) {$.fn.showPopup(2, 'Something went wrong. Please try again.', res)}
})
});
and my script just var_dumps $_POST + $_FILES for now
I console.log'd the FormData using this:
// Display the key/value pairs
for (var pair of slides_data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
and it returns the correct data, so I'm really not sure why my script doesn't get the $_POST data? Am I missing something really obvious?
(if more code is needed - comment and I'll add more)

var slides_data = {};
That is not a FormData object. You need to send a FormData object.
You create one here:
slides_form_data = new FormData(slides_form[0]);
Keep using slides_form_data for all your data. Don't create a second variable and ignore all the work you did to populate the first one.

Related

Ajax: add a variable to a formData

I got a jQuery script which sends info about a picture to a php file through a "formData" variable, like this:
url: 'ajax.php',
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){}
As far as I know, here is the part of the script that generates the content of that formData before it is sent:
function handleFileUpload(files,obj)
{
for (var i = 0; i < files.length; i++)
{
var fd = new FormData();
fd.append('file', files[i]);
var status = new createStatusbar(obj);
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status);
}
}
To catch that data in the php file, I just use
$_FILES['file'][...];
What I would like to do is to simultaneously send an additional javascript variable to the php file, along with the formData, that I would be able to catch as
$_POST['picID'];
How would I do that?
Thank you.
PS the additional javascript variable "picID" is defined at the beginning of the root of the js file so, it should normally be accessible from within any function in that file.
You can append as many key => value to the form data.
fd.append('key', value);
Applying to your scenario,
fd.append('picID', value); //where value is the value of picID
I would recommend that you declare the form data variable fd before the for loop begins. This is because only the file data requires the loop. For additional form data, append them outside the loop
Example
function handleUpload(){
var fd = new FormData();
//commence for loop {
// }end for loop
//append extra key => value
fd.append('key', value);
}

How to output json array value in ajax success?

I have post the data and return the value with json_encode and get that in ajax success stage. but i can't out that data value in specific input. Here is my html input. The return value are show in console and alert box as below.
{"status":"0","data":[{"user_id":"1","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"\u304a\u306a\u307e\u30481"},{"user_id":"31","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"uchida"}]}
<input type="text" id="admin_id" class="form-control">
Here is my ajax
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
alert(result);
}
});
}
Use JSON.parse to get specific input from result
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
var obj = JSON.parse(result);
alert(obj.status);
//alert(result);
var user_id = [];
var start_time = [];
for (i = 0; i < obj.data.length; i++) {
user_id[i] = obj.data[i].user_id;
start_time[i] = obj.data[i].start_time;
}
alert(' First user '+user_id[0]+' Second User '+ user_id[1]+' First start_time '+start_time[0]+' Second start_time '+ start_time[1] );
}
});
}
Use a each loop to get the ids,result is a object that has a data array:
$.each(result.data,function(i,v){
console.log(v.user_id);
//$('.admin_id').val(v.user_id);//use val to append the value, note you have multiple ids so you need multiple inputs
});
if this doesn't work then you return a string not json so you need to convert it to json using:
var result = JSON.parse(result);
Read Following posts you will get idea about json parsing
Parse JSON from JQuery.ajax success data
how to parse json data with jquery / javascript?
and you can try looping like this
var parsedJson = $.parseJSON(json);
$(parsedJson).each(function(index, element) {
console.log(element.status);
$(element.data).each(function(k,v) {
console.log(v.user_id);
});
});
When in an AJAX callback, you can use result.data to access the array of objects being returned. You can work with these like you would any other Javascript object. You may need to deserialize the JSON first.
To accomplish what you're trying to do, the following code would do the trick, although it will only use the very first object in the array as you only have one text box.
var responseObj = JSON.parse(result);
document.getElementById('admin_id').value = responseObj.data[0].user_id;

Using a dynamic variable in an ajax query

I'm struggling to pass a GET variable into a jquery file.
My code is
function upload(files){ // upload function
var fd = new FormData(); // Create a FormData object
for (var i = 0; i < files.length; i++) { // Loop all files
fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
}
fd.append('nbr_files', i); // The last append is the number of files
$.ajax({ // JQuery Ajax
type: 'POST',
url: 'ajax/tuto-dd-upload-image.php?order=5', // URL to the PHP file which will insert new value in the database
data: fd, // We send the data string
processData: false,
contentType: false,
success: function(data) {
$('#result').html(data); // Display images thumbnail as result
$('#dock').attr('class', 'dock'); // #dock div with the "dock" class
$('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
},
xhrFields: { //
onprogress: function (e) {
if (e.lengthComputable) {
var pourc = e.loaded / e.total * 100;
$('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
}
}
},
});
I need the 5 in url: 'ajax/tuto-dd-upload-image.php?order=5' to be the vatriable order passed through a url like domain.com/?order=XX
You can use PHP and export the variable:
var orderId = <?php echo json_encode($_GET['order']); ?>;
function upload(files) {
...
url: 'ajax/tuto-dd-upload-image.php?order=' + orderId,
Or you could parse it directly in javascript:
var orderId = self.location.search.match(/order=(\d+)/)[1];
// Then continue like the previous example
Of course you'll probably need some error checking around this, if there's a chance the GET param might ever be missing.
Try with javascript :
function $_GET(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && result[1] || "";
}
and call $_GET(key) function in your $.ajax request.
var order = $_GET('order');
url: 'ajax/tuto-dd-upload-image.php?order='+order,

Bringing back several variables into ajax form POST success as jQuery variables

I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery

jQuery AJAX referencing $(this) within success function

I have a voting system which sends an id of the clicked item to a PHP script, the PHP updates the database and echos back the new vote counts via an JSON encoded array.
This is the jQuery:
$(".vote_up").click(function(){
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
$(".votes_up").find(id).html(data[x].vote_up);
$(".votes_down").find(id).html(data[x].vote_down);
}
}
});
});
So when i construct the item in the first place, i take the record ID in the database and set it as the items ID. So what i'm trying to do is reference the exact item that was clicked and set it's HTML to the data thats coming back from the PHP. I've checked in Firebug and I'm getting correct data back but the count of votes isnt changing. Any ideas?
This is the PHP for reference:
$query = "SELECT vote_up, vote_down FROM posts WHERE id = '".$id."'";
$result1 = mysql_query($query);
$output = Array();
while ($row = mysql_fetch_array($result1)){
$output[] = Array(
"vote_up" => $row['vote_up'],
"vote_down" => $row['vote_down'],
);
}
echo json_encode($output);
If you just want this in the success: callback to refer to the element that was clicked, just set the context: property for the AJAX request.
$.ajax({
context: this, // set the context of the callbacks
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data) {
// now "this" refers to the element that was clicked
}
You can test it by doing something a little more generic, like:
$(this).html("yep, it works");
... then if that works, consider that it doesn't really make sense to do .html() on the same element in a loop, because each time .html() overwrites the entire content.
Use .append() instead if you're appending data from the loop:
for(var x in data) {
$(this).append(data[x].vote_up);
$(this).append(data[x].vote_down);
}
Wouldn't:
$(".votes_up").find(id).html(...);
Really just need to be:
$('#' + id).html(..);
If you define a variable within the click() method callback, you'll be able to reference it within your ajax success callback. Something similar to this should do you:
$(".vote_up").click(function(){
// Assign the clicked element to a scoped variable...
var target = $(this);
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
// Then refer to it within your callback
target.html(data[x].vote_up);
target.html(data[x].vote_down);
}
}
});
});

Categories