Javascript Text Fields and PHP variable Declaration - php

$(document).ready(function(){
var skillctr = 1;
var experiencectr = 1;
var educationctr = 1;
var achievementctr = 1;
var historyctr = 1;
/*
Add Skills
*/
$("#addSkill").click(function () {
if(skillctr>10){
alert("WOW! But 10 skills are enough.");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'SkillDiv' + skillctr);
newTextBoxDiv.html('<label>Skill No. '+ skillctr + ' : </label>' +
'<input type="text" name="skill' + skillctr +
'" id="skill' + skillctr + '" value="" >');
newTextBoxDiv.appendTo("#SkillsBoxesGroup");
skillctr++;
});
so how can i save the generated fields in my table in database now?
how am i gonna declare the field in php like.. $_POST['skill'].
i need help here. please

Don't use name="skill' + skillctr + '", use name="skill[]".
That way PHP will helpfully create an array that you can loop though:
var_dump($_POST);
foreach ($_POST['skill'] as $skill) {
// save $skill to database
}

You just need to make sure that the input elements you are adding with that javascript are inside a <form>. Then when you submit the form to a php page, you can access the values with $_POST like you wrote above.

Related

jQuery append dict to html, how to insert a auto-incrementing id from 1

How to insert a auto-incrementing id from 1 before info.name in jQuery? I use below code to get aggregated data, for example, each quessionId has many related reasons. Below is my partial code of .js code in jQuery:
function fmtQuestionsByID(id,callback){
if(!DATA.questions[id] || !$('#card_'+id) )return;
var project = DATA.projects[DATA.questions[id].projectId];
if(!project)return;
var issueQuestionLists = DATA.alltags.reduce(function(a,b){
if(a[b['quessionId']]) {
a[b['quessionId']].push({name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']})
} else{
a[b['quessionId']] = [{name:b['name'],color:b['color'],description:b['description'],reason:b['reason'],question:b['question'],issueId:b['issueId'],department:b['department'],_id:b['quessionId']}]
}
return a;
},{});
for(var i=0;i < DATA.questions[id].tags.length;i++){
var lid = DATA.questions[id].tags[i];
for(var l in issueQuestionLists){
var lb = issueQuestionLists[l]
for(var c=0;c< lb.length;c++){
var lc = lb[c];
if(lc._id == lid){
var info = lc;
console.log('info', info);
$('.tags_question').append('['+info.name+']' + info.description + '。' + 'Reason: '+info.reason+ '。' ||'[no data]' );
}
}
}
}
}
And I use below html to get above data
<div id="questioninfo">
<span class="tags_question"></span>
</div>
In the console, I do have those dictionaries, but why the page only get one dict?
Thanks so much for any help.
Thanks so much for Swati's help, to change .html to .append.
You can define a variable which will store the value of count and then whenever you need to print it first increment it and then add that as well with the data which you are already appending .So your code will look like below :
var count = 0; //declare this
for (var i = 0; i < DATA.questions[id].tags.length; i++) {
//..other codes
var lc = lb[c];
if (lc._id == lid) {
count++; //increment
var info = lc;
console.log('info', info);
//add with other datas
$('.tags_question').append(count + '[' + info.name + ']' + info.description + '。' + 'Reason: ' + info.reason + '。' || '[no data]');
}
}

Initializing javascript variables for repeating section in form

I have a form with a repeating section that uses jQuery to clone the section and increment the ids. Now I need to initialize the variables in order to send the form via PHP.
HTML:
<div class="repeatingSection">
<label for="poste_1">Poste :</label>
<input type="text" name="poste_1" id="poste_1"/>
<label for="date_1">Date :</label>
<input type="text" name="date_1" id="date_1"/>
</div>
JQUERY:
jQuery('.cloneButton').click(function(event){
event.preventDefault();
var currentCount = jQuery('.repeatingSection').length;
var newCount = currentCount+1;
var lastRepeatingGroup = jQuery('.repeatingSection').last();
var newSection = lastRepeatingGroup.clone(false).find('.cloneButton').remove().end();
newSection.insertAfter(lastRepeatingGroup);
newSection.find("input").each(function (index, input) {
input.id = input.id.replace("_" + currentCount, "_" + newCount);
input.name = input.name.replace("_" + currentCount, "_" + newCount);
});
newSection.find("label").each(function (index, label) {
var l = jQuery(label);
l.attr('for', l.attr('for').replace("_" + currentCount, "_" + newCount));
});
return false;
});
jQuery(document.body).on('click','.removeButton', function(){
jQuery(this).closest('div.repeatingSection').remove();
return false;
});
PHP :
$poste1 = '';
$date1 = '';
$poste1 = trim($_POST['poste_1']);
$date1 = trim($_POST['date_1']);
I know I would need to put them in an array and loop through them but I'm not sure how to go about it.
You can use a for loop and a count variable from javascript and do something like :
for($i=1; $i<$currentCount; $i++) {
${"poste".$i} = trim($_POST["poste_$i"]);
${"date".$i} = trim($_POST["date_$i"]);
}
You would have variables $poste1 and $date1. Using ${''} creates dynamic variables.

how to set checkbox values and how to get checkbox values in javascript

i want to set value to checkbox,how do it? this is my code: from this code only i could get upto link,image,name value,why? i want to get link,image,name,description,categ value.how do it?
$results=$watch.",".$thumbnail.",".$name.",".$description.",".$val;
<input type="checkbox" name="checkbox[]" id="checkbox[]" class="addbtn" value=<?php echo $results;?>
this is my javascript function to get the checkbox value.
function chkbox() {
$('[name^=checkbox]:checked').each(function() {
var ckballvalue = ($(this).val());
var latlngStrs = ckballvalue.split(",", 5);
var link = latlngStrs[0];
var thumbnail = latlngStrs[1];
var name = latlngStrs[2];
var description = latlngStrs[3];
var categ = latlngStrs[4];
alert(link + thumbnail + name + description + categ);
}
I've tried to revise your code.
When doing it like this it works:
$("input.addbtn").click(function() {
var val = $(this).val();
var arr = val.split(',', 5);
var link = arr[0];
var thumb = arr[1];
var name = arr[2];
var desc = arr[3];
var cat = arr[4];
alert(link + "|" + thumb + "|" + name + "|" + desc + "|" + cat);
});
I hope this helps

how to get file names from input type file in html 5 using javascript or jquery

below is my simple code using HTML 5 multiple file upload. All i need is to grab all the file names not the paths below is simple javascript code
function getFileNames()
{
var path = $('#files').val();
console.log(' path = ' + path);
}
and html form is as
<form action='server.php' method='post' enctype='multipart/form-data' target="iframe">
<input id="files" name='files[]' type='file' multiple>
<input type='button' onclick="getFileNames()">
</form>
when i press the button the console output is as
path = Chrysanthemum.jpg
which is the first name of the file and i want the remaining names , any suggestions , comments are appreciated.
thanks.
well so here i am with the solution after lot of research, in case of input type file the value is stored in array as files with key name.
var files = $('input#files')[0].files;
var names = "";
$.each(files,function(i, file){
names += file.name + " ";
});
alert(names);
fiddle : http://jsfiddle.net/raj_er04/nze2B/1/
pure javascript
function getFileNames(){
var files = document.getElementById("files").files;
var names = "";
for(var i = 0; i < files.length; i++)
names += files[i].name + " ";
alert(names);
}
fiddle : http://jsfiddle.net/raj_er04/nze2B/2/
function getFileNames()
{
var files = document.getElementById("files").files;
for (var i = 0, f; f = files[i]; i++) {
console.log(' name= ' + f.name);
alert(' path = ' + f.name);
}
}
Instead of
var path = $('#files').val();
loop through the array, use
var names = "";
var path = $('#files').each(function(i, el) {
names = names + el.val() + ",";
});

How to put my JSON info into a jQuery Array

I have a project where I've created JSON data for Project Prices/Prices I've gotten this far and pretty much ran into a wall, any help at all would help! I've checked all over the web and on jQuery.getJSON but I wound up getting super confused.
$data = mysql_query("SELECT * FROM xxx")
or die(mysql_error());
$arr = array();
$rs = mysql_query("SELECT product, price FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"products":'.json_encode($arr).'}';
I need to get the product price and product name into this jquery script
$(document).ready(function() {
/*** CONSTANTS ***/
var KEY = 0;
var VALUE = 1;
/*** DEFINE DATA SETS ***/
var POINTS = [ ["$productA", $PRICE ], ["$productB", $PRICE], ["$productC", $PRICE], ["$productD", $PRICE], ["$productE", $PRICE], ["$productF", $PRICE] ];
var SHIPPING_COSTS = [ ["Pickup", 0], ["Next Day Delivery", 30], ["Same Day Print/Same Day Delivery", 65] ];
for (var i = 0; i < POINTS.length; i++) {
$("#quantity").append("<option value='" + POINTS[i][VALUE] + "'>" + POINTS[i][KEY] + "</option>");
}
for (var i = 0; i < SHIPPING_COSTS.length; i++) {
$("#shipping").append("<option value='" + SHIPPING_COSTS[i][VALUE] + "'>" + SHIPPING_COSTS[i][KEY] + "</option>");
}
$("select.autoUpdatePrice, input.autoUpdatePrice").bind("mousedown click change", function(event) {
Calculate();
});
Calculate();
});
function Calculate() {
var net = parseFloat($("#quantity").val());
/* Calculate the magical # by adding the form fields*/
var designFee = $("#abcDesignFee").attr("checked") ? $("#abcDesignFee").val() : 0.0;
var proofFee = $("#abcProofFee").attr("checked") ? $("#abcProofFee").val() : 0.0;
var MyPrice;
MyPrice = parseFloat( parseFloat(proofFee) + parseFloat(designFee) + net + parseFloat($("#shipping").val()));
$("#DumpHere").html("Your Price: $" + formatNumber(MyPrice));
$("#abcName").val($("#quantity").find(":selected").text() + " " + ProductNamePlural);
$("#abcPrice").val(MyPrice);
}
In your PHP script, can you just json_encode() your array of objects without wrapping it in the string? And instead encode the JSON object like so:
<?php
// your script ...
echo json_encode($arr);
This creates an array of JSON encoded objects:
[{"name":"item 1","price":4.99},{"name":"item 2","price":9.99}]
Make an AJAX request in your JS to query your PHP script, and use jQuery's $.each() and $.parseJSON() methods to iterate over the returned JSON data:
$.post('get_products.php', { data: foo }, function(json) {
$.each($.parseJSON(json), function(key, product) {
console.log(product.name + ' ' + product.price);
});
});
Hope this helps :)
When I was learning - I had exactly the same problem - but it got answered here
What I didn't realise at the time was that you can use object notation (which is the ON of json) to access the data you sent.
If you look at my question and the answer I selected, once you have sent the data back to javascriot you can access it easily. In my example it would be as straitforward as using data.catagory_desc in javascript to find the data that was encoded.

Categories