Passing multiple form data to PHP controller - javascript

$('#save').on("click", function() {
//collect the form data while iterating over the inputs
var data = [];
$('[name=form]').find('input, select, textarea').each(function() {
if ($(this).attr('value') != '') {
var name = $(this).attr('name');
var value = $(this).attr('value');
data[name] = value;
}
})
for (var i = 1, ii = form.length; i < ii; i++) {
var name = 'form' + i;
$('[name=' + name + ']').find('input, textarea').each(function() {
data[i] = [];
if ($(this).attr('value') != '') {
var name = $(this).attr('name');
var value = $(this).attr('value');
data[i][name] = value;
}
})
}
$.post('foo', data,
function(data) {
console.log(data);
I have the above jquery code where I wish to post multiple form data into my PHP backend controller.
In my controller, I used
$input = Input::all()
Question 1
How do I access the data in the array that I have passed?
Let's say I have foo input and bar input in my form. I tried to use
$input['foo']
$input['bar']
but I'm getting internal server error with undefined index error.
Question 2
How do I access the data of the data[i][name]? Let's say I have form1, form2, form3, so it my data array will become
$data[1][foo]
$data[2][foo]
$data[3][foo]
How can I access these in my PHP controller?
Thanks and sorry for the long question

with FormData object.
var formdata = new FormData();
formdata.append("name", value);
on server-side you read values like this:
$name = $_POST["name"];

Related

How to pass Decoded Parameter in document.createElement("input") JavaScript

The Below code passes required parameter to value but send URI encoded parameters like Page=2%26range%3D0.00Mb%2BTO%2B14.00Mb%26file_type%3DDOC%26file_type%3DDOCX but howto send decoded parameter value like Page=2&range=0.00Mb TO 14.00Mb&file_type=DOC&file_type=DOCX
var para_wotext="";
var com_para=location.search.substring(1).split("&");
$.each(com_para, function( index, value ) {
if(((value.indexOf("cores")) < 0) && ((value.indexOf("textSearch")) < 0) )
{
para_wotext+="&"+value;
}
});
console.log("para_wotext"+para_wotext);
prints in console as :
2&range=NONE&file_type=PDF&file_type=XLS which is correct
if(!document.getElementById("search-form").Page)
{
var hidden = document.createElement("input");
console.log(hidden);
hidden.type = "hidden";
hidden.name = "Page";
hidden.value = pageNum+decodeURIComponent(para_wotext).toString();//passing decoded parameter
var f = document.getElementById("search-form");
f.appendChild(hidden);
console.log(f);
}
f.submit()
but by Calling f.submit() the submitted form gets prameters as Page=2%26range%3D0.00Mb%2BTO%2B14.00Mb%26file_type%3DDOC%26file_type%3DDOCX
if you want to decode Data then use this one where Page is your data
var Page ='2%26range%3D0.00Mb%2BTO%2B14.00Mb%26file_type%3DDOC%26file_type%3DDOCX';
var uri_dec = decodeURIComponent(Page);

JSON array to and from MySql. Saving and Looping

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

How can I dynamically create unique objects within .each()?

I'm running a .each() on a list of items and categorizing those items in my HTML. In a function after that I'm checking which of those items is checked (checkboxes). In my function (prepareTrainings();) that finds which boxes were checked, I need it to display data from the result of the .each(). Basically, if the user checked X checkbox, show the Course Name and URL for that item...
My question: I'm not sure what would be best practice. Should I be creating an object to store those values inside my if(trainingGroup etc.) statements?
$.ajax({
url: "mySite",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(index) {
var $this = $(this);
var courseName = $this.attr('Title');
var courseNumber = $this.attr('Course_x0020_Number');
var courseUrl = $this.attr('URL');
var trainingGroup = $this.attr('Training_x0020_Group');
var recurrence = $this.attr('Recurrence');
var dynCourseId = courseName.replace(/\s+/g, '')
if (trainingGroup == 'Group1') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('officeListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+dynCourseId+'"/>'+courseName+recurrence+'</li></ul>';
}
if (trainingGroup == 'Group2') {
if (recurrence == "Don't Specify") {recurrence = '';
} else recurrence = " ("+recurrence+")";
document.getElementById('labListSpan').innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+dynCourseId+'"/>'+courseName+recurrence+'</li></ul>';
}
});
},
error: function(){
alert("Failed to query SharePoint list data. Please refresh (F5).");
}
});
function prepareTrainings() {
var idSelector = function() {
return this.id;
};
var checkedCourses = $(":checkbox:checked").map(idSelector).get();
alert("IDs for Courses Selected: " + checkedCourses);
}
Keeping your processed objects in a global var makes sense. Define e.g. an object like so:
var courses = {};
Then in your .each function, extract the information from your HTML elements like you already do and store each result in another object:
$.each(data.d.results, function(index) {
var $this = $(this);
var course = {}; //Create empty object
course.name = $this.attr('Title');
course.number = $this.attr('Course_x0020_Number');
course.url = $this.attr('URL');
course.trainingGroup = $this.attr('Training_x0020_Group');
course.recurrence = $this.attr('Recurrence');
course.id = course.name.replace(/\s+/g, '')
//Store your course by id in the courses object
courses[course.id] = course;
//...
Later when checking which checkboxes are checked, you can retrieve the information of each course like so:
var checkedIDs = $(":checkbox:checked").map(idSelector).get();
var course = courses[checkedIDs[0]]; //fetches the first selected course
//Now you can do whatever with the data, like print lists...
(...).innerHTML += '<ul class="courseLists"><li><input type="checkbox" id="'+course.id+'"/>'+course.name+course.recurrence+'</li></ul>';
I hope I understood your question correctly, if not leave a comment.

Cookie is overwriiting issue

I have following code I use Jquery cookie plugin to set cookie.I need to store multiple values to a a cookie variable using jquery but every time its overwrite so multiple value doesn't store.please have a look into my code and help me.I have a select box and its name is inserted into a cookie variable every time.
$(".cookieul").on("click",function(){
var a ='';
var myCookies = [];
var newValue = $(".client option:selected").text();
a += newValue;
myCookies.push(a);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
});
You may write like this -
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();// your new selected text
var old_value_json = $.cookie("example"); // check your plugin get cookie syntax
var old_value_arr = [];
old_value_arr = $.parseJSON(old_value_json); //converting your stored JSON string to javascript array
old_value_arr.push(newValue ); // pushing new value to array
$.cookie("example", JSON.stringify(old_value_arr ), { expires: 7 });//setting new value to cookie
});
This solves the issue.Any other better way
var myCookies = [];
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();
var old_value_json = $.cookie("example");
myCookies = $.parseJSON(old_value_json)
myCookies.push(newValue);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
var storedAry = JSON.parse($.cookie('example'));
console.log(unique(storedAry));
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
});

Splitting up a string and passing it to a function

I am having some trouble trying to pass string objects to a function. In the query string of the url I pass fields which is a comma delimited string containing the attributes of interest.
I put the names of those attributes in the fields array. However now I am having trouble passing that information to a function.
In the code below the query.pluck('id', 'name') works, the query.pick( fieldString ) does not.
I am stuck on this one, how can I pass the attribute names in the fields array to the function so it will work?
Please advice.
var log = require('logule').init(module,'query');
var url = require('url');
module.exports = {
build : function(req, entity, callback) {
var isCollection;
isCollection = req.params.id? false: true;
var query = req.rethink.table(entity);
parsedUrl = url.parse(req.url, true);
console.log(isCollection);
if (parsedUrl.query.fields) {
var fields = parsedUrl.query.fields.split(',');
var total = fields.length;
fieldString = fields[0];
for (var i = 1; i < total; i++) {
fieldString += ', ' + fields[i];
}
if (isCollection) {
var query = query.pluck('id', 'name');
} else {
var query = query.get(req.params.id).pick( fieldString );
}
}
return callback(null, query);
}
}
You don't need to put fields in a string, just use
var query = query.get(req.params.id).pick.apply(this,fields);
You need to use the "apply" function with the function name, and an array of parameters (fields in your case)
var query = query.get(req.params.id).apply('pick', fields);

Categories

Resources