I have a simple HTML Form and in this form there is a section where the user can select one or more checkboxes.
I have written a JS function that gets the value of every checked box and puts it into a string:
function getSupportedDevices() {
var supportedDevices = "";
$('.devices:checkbox:checked').each(function () {
let sThisVal = $(this).val();
supportedDevices += sThisVal + ";";
});
console.log(supportedDevices);
return supportedDevices;
}
This function is called before the Ajax call and the result should be appended to the FormData so that I can use the string later on.
Here is the code from where I try to add the list:
var $debForm = $('#formDeb');
if ($debForm.length > 0) {
$debForm.on('submit', function (event) {
event.preventDefault();
if (!isSubmitting) {
let $form = $(this);
let targetUrl = $form.attr('action');
let method = $form.attr('method');
let $btnSubmit = getElement($form, '.js-btn-submit');
var myFormData = new FormData(this);
var supportedDevices = getSupportedDevices();
myFormData.append("supportedDevices", supportedDevices);
$.ajax({
type: method,
url: targetUrl,
data: myFormData,
async: true,
beforeSend: function () { ...
Running this code throws an error:
Uncaught TypeError: Illegal invocation
at add (jquery.js:8430)
at buildParams (jquery.js:8417)
at Function.jQuery.param (jquery.js:8450)
at Function.ajax (jquery.js:9040)
at HTMLFormElement. (submitdeb.js:45)
at HTMLFormElement.dispatch (jquery.js:5206)
at HTMLFormElement.elemData.handle (jquery.js:5014)
Line 45 is $.ajax. If I try data: new FormData(this).append("supportedDevices", getSupportedDevices()) as ajax parameter I get no error but the $_POST Array is empty.
What am I doing wrong that I get this error? The function to generate the string works on it's own and if I only send the FormData without anything appended, the $_POST Array is not empty.
Set processData:false to prevent $.ajax trying to serialize the FormData object using $.param() which it does by default when an object is passed to data.
The browser will handle the serializing internally
Related
I am trying to post data to an php site which only contains php code which should be executed when the ID #mR-RateableFramePicture is being clicked on the first page. This is being done by a ajax request:
$('#mR-RateableFramePicture').dblclick(function() {
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: { rateableUserID: rateableUserID, rateablePictureID: rateablePictureID},
success: function() {
$('#DynamicContent').load('moduleRateable/scriptSavedStyle.php');
}
});
});
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
And here the url destination which ajax posts to:
<?php
// Start the session (enable global $_SESSION variable).
session_start();
// Include database-link ($conn).
include '../../scriptMysqli.php';
// Make global variable to simple variable.
$userID = $_SESSION["ID"];
//Save the rateable style to one owns libary of saved styles.
$ratedUserID = $_POST['rateableUserID'];
$ratedPictureID = $_POST['rateablePictureID'];
$sql = $conn->query("UPDATE styles WHERE userID = '$ratedUserID;' AND
pictureID = '$ratedPictureID' SET savedByUser = '$userID'");
?>
I get the following error messages:
Notice: Undefined index: rateableUserID in C:\xampp\htdocs\mystyle\app\moduleRateable\scriptSavedStyle.php on line 12
Notice: Undefined index: rateablePictureID in C:\xampp\htdocs\mystyle\app\moduleRateable\scriptSavedStyle.php on line 13
You are not passing the value of the variables rateableUserID and rateablePictureID in your $.ajax({}) call like below -
data: { rateableUserID: rateableUserID, rateablePictureID: rateablePictureID}. Unless they are defined globally you will get undefined value at the PHP end.Make sure you have the value assigned to rateableUserID and rateablePictureID before you make the call. However still you have to check whether you are actually passing that variable in your post request or not because PHP cannot find the key name.
The function should be like below
$('#mR-RateableFramePicture').dblclick(function() {
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: { "rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function() {
$('#DynamicContent').load('moduleRateable/scriptSavedStyle.php');
}
});
});
So I have searched around a bit in hopes of finding a solution to my problem, but have had no luck.
I am basically trying to pass data into the ajax function, but when it passes it to my php file it only returns an empty array (Yes there are a few topics on this, couldn't find any to fit my needs) , here is the console output: Array ()
Its odd because just before the ajax function I log the data, and it prints out each section with no problems.The posting URL is accurate, works fine straight from my form. I have tried to use response instead of data passed through the function, but no luck their either.
Thanks in advance!
Here is the JS file
$(document).ready(function() {
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
return false;
});
});
And here is my PHP
<?php //removed the issets and other checkers for ease of readability
print_r($_POST);
?>
UPDATE: I have tried to add method:"POST" to my ajax function and it still seems to be printing out blank arrays... Maybe I should convert everything to GET?
jQuery ajax() uses GET as default method. You need to mention method: POST for POST requests.
method (default: 'GET')
$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
Or you can also use post().
EUREKA!!! Wow, the mistake was much simpler than I thought, figured it out solo! Thank you everyone for the tips! Finally got it
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {}; // THIS NEEDS TO BE CHANGED TO BRACKETS!!
This is probably a basic question because I'm not particularly good at javascript and don't understand closures etc. So I'm having trouble getting variable values to pass into the call backs. In this code, how can I get the value of id to pass to the success function handler so it's available when the function returns back?
$(document).on("click","#media-edit-form .fancybox-submit", function(event){
var form = $(this).parents('form:first');
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var postData = form.serializeArray();
var id = postData["id"];
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var jqxhr = $.ajax(
{
url: form.attr('action'),
type: 'POST',
data: postData,
headers: {'X-CSRF-TOKEN': token},
}
)
.success(function(xhr) {
var refreshZoneId = '#image-block' + id;
var refreshZone = $(refreshZoneId);
alert('refreshing');
})
.fail(function() {
alert( "error" );
});
});
I think the problem is not with the variable, but with the value assigned to it.
Try
var id = $('input[name="id"]').val();
The problem is serializeArray() returns an array so postData is an array not an object so postData["id"] should return undefined which might be your problem.
I am doing an Ajax request on an XML file and mapping the XML into a JavaScript object my problem is that am logging the object and seeing the values I won't but when I try to return the values I keep getting undefined, even that all the code is inside the success callback of the AJAX request, my code is as bellow:
// Errors Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
// Ajax Request
$.ajax({
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
$(xml).find('EcaAdminBc').each(function () {
var code = $(this).find('code').text();
var msg = $(this).find('msg').text();
ErrorsObject[code] = msg;
});
// Reformat Errors
if(ErrorApplet.length > 0) {
$(ErrorApplet).each(function(){
var Error = $(this).text();
if(Error.indexOf("SBL") >= 0){
var ErrorCode = Error.split('(')[1].replace(")","");
var ErrorText = ErrorsObject[ErrorCode];
// The Log is showing the values correctly but i cant access the object values
console.log(ErrorsObject);
// ErrorText And ErrorCode Are always undefined !!
if(typeof ErrorText != 'undefined'){
$(this).text(ErrorText);
}
}
});
}
}
});
I need additional context, but I guess what the problem is. You are trying to do some thing like this:
var myFunction = function(){
// Error Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
$.ajax(
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
//using response to fill ErrorsObject
ErrorsObject['Ok'] = 'This key has Value!';
//more awesome code here
//... lets check again:
console.log(ErrorsObject['OK']); //Outputs 'This key has Value!'
}
);
return ErrorsObject;
};
var myAwesomeErrorObject = myFunction();
console.log(myAwesomeErrorObject['OK']); //undefined!
console.log(myAwesomeErrorObject); //Empty object!
The problem is that myFunction finished before the success callback function gets executed (the callback is asynchronous). That is why logging myAwesomeErrorObject['OK'] shows undefined. I guess that you also tried return ErrorsObject inside the success callback, but that won't work either.
In order to fix your code you must either:
Use the ErrorsObject inside the success callback (i.e. don't return it).
Call a second function from inside the success callback, passing it the ErrorsObject.
Pass a calback function to myfunction and execute it from inside the success callback.
var model = new Array();
function saveItem(id){
var title = $("#inputTitle_"+id).val();
var url = $("#inputPicurl_"+id).val();
var content = $("#content-editor-"+id).html();
model[id] = new Array();
model[id]['inputTitle'] = $("#inputTitle_"+id).val();
model[id]['inputPicurl'] = $("#inputPicurl_"+id).val();
model[id]['author'] = $("#author_"+id).val();
model[id]['content'] = $("#content-editor-"+id).html();
$("#title_"+id).text(model[id]['inputTitle']);
console.log(model);
}
$("#submit_form").click(function(){
$.ajax({
url:'materials/addpics',
type:'post',
dataType:'json',
data:model,
traditional:'true',
success:function(data){
console.log(data)
}
});
});
when the saveItem() run,the console log is array[],but the data named model in ajax is NULL?
"when the saveItem() run, ..." saveItem is never run. You've defined the function, but you haven't called it anywhere in your code. You probably meant it to be the success handler, instead of the handler you've got that just logs data. (Except that the argument to saveItem doesn't seem to match the argument supplied to the handler.)