jQuery AJAX pass form data and an array to PHP - php

I am trying to pass some HTML form data as well as a global array to PHP via AJAX. I know how to pass an array, and I know how to pass serialized form data. But how do I pass both at the same time? I have tried data: { formData, arrGFormId: arrGFormId }, but it doesn't work.
Edit: The form is just a simple HTML form with some inputs. My array values come from another AJAX call and are pushed into the global array arrGFormId.
function validateForm3(){
jQuery.ajax({
type: "POST",
url: "community_form_add.php",
async: false,
data: { arrAdminList: arrAdminList },
}).done(function(rs){
var sResult = rs.sResult;
var arrFormId = rs.arrFormId;
Array.prototype.push.apply(arrGFormId, arrFormId);
})
})
var arrGFormId = [];
jQuery('#formCreateForm').submit(function(e){
e.preventDefault();
var formData = new FormData(jQuery(this)[0]);
formData.append('sAction', 'submitForm');
jQuery.ajax({
type: "POST",
url: 'community_form_add.php',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
jQuery('.load_ball').css("display","block");
},
success: function(data)
{
jQuery('.load_ball').css("display","none");
jQuery('.cover').css("display","block");
jQuery('.popUpSubmitSuccess').fadeIn(300);
}
})
});

You need to encode the array, then you can add it to the FormData. You can convert it to JSON.
formData.append('arrGFormId', JSON.stringify(arrGFormId));
Then in PHP you can use json_decode($_POST['arrGFormId']).

you can use hidden input inside the existing form. the value of the hidden inputs are the array. so you only pass formData through ajax.

Related

jQuery post form with static value from funnction attributes

I have a funnction to post and recive form to another php file. I don't know why, but the php file has return empty array.
the function has two attributes "name" and "arg" and wants to send these two values ​​to the file steel_th_dynamic_query.php, then display what it returns in the div "demo". I think the problem is on the line data: { but I don't know why it doesn't work.
function displayPhrase(name, arg){
//document.getElementById("demo").innerHTML = name + ' ARG: ' + arg;
$.ajax({
url: './modules/settings/steel_th_dynamic_query.php',
data: {
MyData: name,
MyARG: arg
},
processData: false,
contentType: false,
type: 'POST',
success: function(data){
document.getElementById("demo").innerHTML = data;
}
});
}
You need to remove the processData and contentType properties, or at least set them back to their default values. Setting them to false is only required when sending binary data in the request, ie. a FormData object.
function displayPhrase(name, arg) {
$.ajax({
url: './modules/settings/steel_th_dynamic_query.php',
type: 'POST',
data: {
MyData: name,
MyARG: arg
},
success: function(data) {
$("#demo").html(data);
}
});
}

Ajax store response json in variables

The response of success ajax call is in the form of json like this one:
{"prize_name":"Keys 4","prize_image":"http:\/\/localhost\/web-game-w\/wp-content\/uploads\/2017\/09\/4rare.jpg"}
How I can store "prize_name" & "prize_image" in variables for later use?
Here is the ajax code:
$("#ajax").click(function(e){
e.preventDefault();
var data = {
'action': 'getprize_data',
dataType: "json",
async: false
};
$.post(ajaxurl, data, function(response) {
console.log(response);
// Store vars
});
});
Also I have an issue. This response.prize_name will return error response.prize_name is undefined.
declare those variables without using var before the ajax call starts and assign the values to those variables in the success function
prize_name = prize_image = "";
$("#ajax").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: ajaxurl, // give url over here
data: {action: 'getprize_data'},
dataType: 'json',
async: false // always avoid false if you can
success: function(response) {
console.log(response);
response = JSON.parse(reponse);
// Store vars
// assign the values over here
// maybe you will need to decode the json
// if you are encoding it so use JSON.parse
// for decoding the json
},
});
});
Now the reason why I'm saying to declare variable without using var is because
If you don't use var , the variable bubbles up through the layers of
scope until it encounters a variable by the given name or the global
object (window, if you are doing it in the browser), where it then
attaches.
Your post call is wrong. I'd suggest to avoid async to false. But, if you need at all cost such a behavious you can rewrite your post as:
$.ajax({
type: "POST",
url: ajaxurl,
data: {action: 'getprize_data'},
success: function(response) {
......
},
dataType: 'json',
async: false
});
Instead to create global variables you can take advantage of data attributes.
You can store the values in this way:
$('#ajax').data('prizeName', response.prize_name);
And, in future, when you need such a value you can simply get the value with:
$('#ajax').data('prizeName');
Remember that ajax is asynchronous so the value will be available only when the succes callback will be executed. Hence, I suggest to use a callback function in your ajax success function.

PHP Ajax Post File and Text Same Time

I can post only image and get it with $_FILES['foto']['name']. I need post image and text same time.
var fotoFile = new FormData();
$('#foto').on('change', function (evt) {
var files = evt.target.files;
if (files.length > 0) {
fotoFile.append("foto", files[0]);
}
});
It is post code
` $.ajax({
url: 'postpages/personelsave.php',
dataType: 'text',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: {foto : fotoFile, tc_no : document.getElementById('tcNo').value},
success: function(php_script_response){
alert(php_script_response);
}
});`
and personelsave.php
$_FILES['foto']['type']
$_POST["tc_no"]
Error : undefined index foto.
What is wrong with it?
You can't use multiple dataTypes, if you use JSONP this will return a jsonp block which you could use to call a callback to handle the return data like this:
Basic example of using .ajax() with JSONP?
So through JSONP you can handle multiple dataTypes.
Just use below to submit all types of input data including file
var formData = new FormData($("#formID")[0]);
$.ajax({
type: "POST",
url: 'postpages/personelsave.php',
data: formData,
processData: false,
contentType: false,
});

ajax send file and variable to php

I'm using an ajax call to upload a file, handled by PHP. The file should be placed in a specific directory based on a jquery variable. I can get the file to upload, but cannot pass the variable along with the file. PHP reports an undefined index error.
Ajax code:
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
I tried changing the data property to "fd+'&myVar='+myVar, however PHP cannot parse the data correctly and returns undefined index error for both the $_FILES['file'] variable as well as the $_POST['myVar'] variable.
How can I send both the file and a variable?
If you need another form field, call fd.append a second time:
fd.append('file', document.getElementById('select').files[0]);
fd.append('myVar',myVar);
You can append values other than files to a formdata object.
var fd = new FormData();
fd.append( 'file', document.getElementById('select').files[0]);
fd.append( 'myVar', myVar);
$.ajax({
url: 'test.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function(e){
// some code here
}
});
Refer to $.ajax jQuery API Documentation.
It is clearly stated that data should be an object with key-value pairs representing data accepted by server-side script. Whatever, not sure why jQuery seems to not accept your data. Maybe you should try this out manually.
Since your test.php accepts POST data as myVar your jQuery Ajax configuration should probably look like
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myVar: document.getElementById('select').files[0]
},
success: function(e){
// some code here
}
});

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

I have been trying to submit a form with enctype="multipart/form-data". I have this setting because the form will involve jpeg/png uploads once I have figured out the ajax submission for text inputs.
the php works fine when referencing the script using action within the form html.
the form data seems to be retrieved correctly by the below jquery because the alert line shows: productName=Test+Name&productDescription=Test+Description&OtherProductDetails=
the returned data printed to my HTML by the jquery success function is a php error saying:Undefined index: productName
removing contentType:false fixes the problem.
When i google jquery/ajax multipart/form-data submission, the top hits at least mainly include 'contentType:false'. Please could someone explain the reason to me?
http://digipiph.com/blog/submitting-multipartform-data-using-jquery-and-ajax
http://hayageek.com/jquery-ajax-form-submit/
Sending multipart/formdata with jQuery.ajax
The jquery API documentation says:
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type.
Why would we need to set it to false for a multipart/form-data submission?
When would the false setting be needed at all?
Jquery:
$("#addProductForm").submit(function (event) {
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#productFormOutput").html(returndata);
alert(formData);
},
error: function () {
alert("error in ajax form submission");
}
});
return false;
});
contentType option to false is used for multipart/form-data forms that pass files.
When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
To try and fix your issue:
Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false.
Try using new FormData instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log().
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});

Categories