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.)
Related
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
using the following code i try to get data of 2 getjson calls into array only when both getjson called completed. The code give me this error:
resultFromUrl1.feed is undefined
var entry1 = resultFromUr11.feed.entry;
i looked at f12 i saw both getjson executed successfully but no data get put into the array! how to fix this error ? furthermor should i use $.when(url1Promise, url2Promise).then or $.when(url1Promise, url2Promise).done ?
<javascript>
var files = new Array();
function pushtoArray() {
//first getjson call
var url1 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url1Promise = $.getJSON(url1, function (data) {
console.log("url1 success");
});//end of ajax call
//second getjson call
var url2 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url2Promise = $.getJSON(url2, function (data) {
console.log("url2 success");
});//end of function
$.when(url1Promise, url2Promise).then(function (resultFromUrl1, resultFromUrl2) {
var entry1 = resultFromUrl1.feed.entry;
var entry2 = resultFromUrl2.feed.entry;
var entry = entry1.concat(entry2);
$(entry).each(function () {
// Column names are name, age, etc.
count++;
files.push({ url: this.gsx$url.$t, filename: this.gsx$name.$t });
alert(files.length);
print_r(files);
console.log(files);
});
});
}//end of function
</javascript>
<body onload="pushtoArray()">
jQuery ajax functions are a bit of a pain to use with $.when(). What is is in resultFromURL1 is actually an array of three values like this: [data, textStatus, jqXHR].
So, you need to change to:
var entry1 = resultFromUrl1[0].feed.entry;
var entry2 = resultFromUrl2[0].feed.entry;
In addition, you should add an error handler to your $.when().then() construct so you can see if any errors occurred in your getJSON() calls.
I tried your example using this url: "https://spreadsheets.google.com/feeds/list/o13394135408524254648.240766968415752635/od6/public/values?alt=json"
It works fine..
You are receiving data. You can access the data by writing
resultFromUrl1[0].feed.entry
resultFromUrl2[0].feed.entry;
I'm a learner and i'm facing a problem. First i made a variable. then with a ajax function i have got a json data. then i parsed it and tried to pass the json data to my variable named var invoice_details. Then with a click event i tried to see the variable but its showing only 0. but my console.log(parsed); command under ajax function showing the json data on my console log. but the console.log(invoice_details); on my action function showing 0. What wrong with me?
//function order started
var invoice_details;
function order(val1){
var order_no=getQueryVariable("order_number");
//AJAX START
$.ajax({
url: "/anamika/function/order.php",
type: "POST",
data: {item_code: item_added, paymentdetails: val1, order_no: order_no },
success:function(data, textStatus, jqXHR)
{
//console.log(data);
var parsed = JSON.parse(data);
var invoice_details = parsed;
console.log(parsed);
},//Success finished
error:function(jqXHR, textStatus, errorThrown)
{
} //Error finished
}) //AJAX FINISHED
}
//function order finished
order('91');
$("#invoice_pay").live("click", function (event) {
console.log(invoice_details);
})
When you declare var invoice_details = parsed; inside the success callback, you are actually creating a new local variable that lives only on the scope of the success callback, and hence this new local variable is getting your data and not the global one you're then performing the console.log on.
You already defined that variable on the outside, so just remove the var declaration and do:
invoice_details = parsed;
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.
So, I've got the below code: -
function testing(results) {
$table = $('#formList')
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
}
It basically takes a JSON file and then adds the data into the right sub tables within a main table via appends etc.
The oddity is during debug I had an alert in there to check the html of the table it was identifying (making sure it had found the right sub table etc) and all worked well. But if I remove that alert it then suddenly only appends all the data to the last sub table in the main table?! Any clues?
It's a classic JavaScript closure-loop problem. The variables defined in the for loop are being reassigned each time within the loop and responses from the AJAX requests(which are async) get appended to the last sub-table. It works when you have an alert because the variables have not been reassigned(as alert blocks the for loop execution) by the time AJAX request is completed.
You could handle this by having a function do the AJAX request and append. The variables are not reassigned within this function and hence should work.
function testing(results) {
$table = $('#formList')
function appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal){
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal);
}
}
Without seeing more of your code, I can't say for sure. But when I had a similar issue it was because I was using append outside of my $(document).ready(function(){ /*stuff here*/ })
Essentially the object I was appending to hadn't loaded yet.
in your Ajax call use its argument 'async';
it accepts Boolean value, pass the value 'false' in it.
Try it
Move
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
To your callback function:
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
$subTable.append(data);
}).done(function(){});