question relates to PHP and Javascript
for now every table has a form with input tags that each of them has id="field_from_table"
GLOBAL_TABLE=name of that table
GLOBAL_FIELDS=name of fields in that table
GLOBAL_ID=ID value for table.
every field also have a label for im.
some of the fields are not text.
I want to get/set those input tags.
now it's design like this:
<script>
function get()
{
id=GLOBAL_ID
$.post("handle.php",{type:"get",tablename:GLOBAL_TABLE,fields:GLOBAL_FIELDS,id:GLOBAL_ID),function(data)
{
fieldValues=/*javascript explode data*/;
foreach(/*array of fields as idx=>fieldName*/)
{$("#"+fieldName)=fieldValues[idx];}
}
function set()
{
/*for each GLOBAL_FIELDS as idx=>fieldName
values[fieldName]=$("#"+fieldName).val;
*/
valuesI=/*implode values*/;
$.post("handle.php",{type:"set",tablename:GLOBAL_TABLE,fields:GLOBAL_FIELDS,values:valuesI),
function(data)
{
if (data!=null) alert ("error");
}
}
</script>
handle.php updates the information into table and fields.
or selects and outputs CSV.
problem is that i need to output a field list from php so javascript can use it
and i don't think that using javascript that way is a good idea
is there a better design.
a good answer or an advice is most appreciated.
arye
try this:
<script>
function get()
{
$.post("handle.php",{type:"get",tablename:GLOBAL_TABLE,fields:GLOBAL_FIELDS),function(data)
{
var fieldValues = data.split(','),
fieldNames = GLOBAL_FIELDS.split(',');
for(var ind = 0; ind < fieldNames.length; ind++) {
$("#"+fieldName[ind])=fieldValues[ind];
}
}
});
}
function set()
{
var fieldValues = "",
fieldNames = GLOBAL_FIELDS.split(',');
for(var ind = 0; ind < fieldNames.length; ind++) {
valuesI += ((fieldValues.length == 0) ? "" : ",") + unescape($("#"+fieldName[ind]).val());
}
$.post("handle.php",{type:"set",tablename:GLOBAL_TABLE,fields:GLOBAL_FIELDS,values:valuesI), function(data)
{
if (data!=null)
alert ("error");
}
});
}
</script>
Related
function getPublicLink() {
var div = document.getElementById('links'); // anchor tag
var url;
for(var x in div){
url += div[x].href;
}
}
This is for getting the list. My Problem is that I want to compare it with the json results below. If there is a matched. I will alter the anchor tag to remove the href attribute or make the text Connected ( Now it is "Invited"). The Linkedin connection code is:
function displayConnections(connections) {
var members = connections.values;
var publicUrl;
for(var member in members) {
publicUrl += members[member].publicProfileUrl;
}
}
My problem is they are in a big string. What i want is to compare them one by one. I'm out of ideas since I'm just a JS beginner. Thanks for your input!
I've found the answer.
for(var i in publicUrl) {
for(var j in url) {
if(url[j] === publicUrl[i]) {
alert("Found " + url[j]);
}
}
}
I have some javascript sorting my ul, alphabetically a-z or z-a. It works fine on page one, but if there is more than one page it ignores the list on page 2 etc.
So, instead of using javascript to sort the li's, I want to pass the selection back to the page's query and reload
here's my script, most of which is redundant now.
var select = document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
} else {
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
});
So I want to detect the selected dropdown value (either A or Z) and pass that into the url and reload. I'm stuck ;-?
Rich :)
I am not sure this is the best way to approach the problem, and maybe you should elaborate what doesn't work with your pagination. In any case, you can achieve what you need to do by doing something like this (explaination in the code comments):
var queryString = {};
// Get the previous query string with a little help from PHP
// this shouldn't be a problem since you are already using PHP
// for your project.
queryString = <?php json_encode( $_GET ); ?>;
$('#organise').change( function() {
// Set the sort property of the object to the value of the select.
queryString.sort = $(this).val();
// jQuery will help you serialise the JSON object back to
// a perfectly valid query string (you may want to escape
// characters)
newQueryString = $.param( queryString );
// Append the new query string
window.location = newQueryString;
});
This function will properly check if you already have any query string and preserve that; also, if the user changes the select multiple times, it will not add up several query strings.
you can change the url and pass the param with
document.location.href = document.location.href + "?arg=" + document.getElementById("organise").value;
You can use localstorage for this if you don't want to show in url
For example:
function Ascending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? 1 : -1;
});
}
function Descending()
{
$('.recipeTable li').sortElements(function(a,b){
var aText = $.text([a]);
var bText = $.text([b]);
return aText.toLowerCase() > bText.toLowerCase() ? -1 : 1;
});
}
if(localStorage.order=='A')
{
return Ascending();
}
else
{
return Descending();
}
var select=document.getElementById('organise');
$('#organise').change(function() {
if(select.value === 'A') {
localStorage.order=='A';
return Ascending();
} else {
localStorage.order=='Z';
return Descending();
}
});
Refer more for localStorage on http://www.w3schools.com/html/html5_webstorage.asp
I know this question has been asked before, but I wasn't able to find any answers that are up to date or functional (at least for my application).
My JQuery autocomplete box is using a mysql database as its source. I want the user to be able to type to get recommendations, but then is forced to select from the dropdown choices before they can submit the form.
My Javascript:
<script type="text/javascript">
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 5
});
});
var inputs = {college: false};
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
alert('incorrect');
return false;
}
}
alert('correct');
$('#college_select_form').submit();
});
</script>
My form:
<form action="choose.php" method="post" id="college_select_form" name="college_select_form">
<input type="text" id="college" name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
</form>
Search.php:
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
So what would be the best approach to doing this? The only solution I can think of is using PHP to verify that the textbox's value matches a value in the database, but I'm not sure how to implement that with my current code.
You should always check it in "choose.php" (server-side) since the user can disable the JavaScript and post whatever they want in the inputs of your form
$college = mysql_real_escape_string($_GET['college']);
if ($college != "" || $college != null || $college != -1)
{
//DO STUFF
}
NOTE: YOU SHOULD ALWAYS USE "mysql_real_escape_string" to prevent SQL Injection!
more info: http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
So accordingly in search.php change the
$ac_term = "%".$_GET['term']."%";
to
$ac_term = "%". mysql_real_escape_string($_GET['term']) ."%";
You can also check the form before the user submit to just make it more user friendly (users don't want to wait couple of seconds for the page to gets refreshed with errors on it!)
so maybe something like this would help: Submit Event Listener for a form
function evtSubmit(e) {
// code
e.preventDefault();
// CHECK IT HERE!
};
var myform = document.myForm;
myform.setAttribute('action', 'javascript:evtSubmit();');
In my project i handled it by checking on focus-out , if the text entered in the autocomplete field actually matches my dropdown options.If not i will simply remove it.
change: function(event, ui) {
if (!ui.item) {
this.value = '';
}
}
See my full example here-Jquery auto comp example
it has an embeded fiddle,you can check the fiddle directly also
http://jsfiddle.net/9Agqm/3/light/
Add this code to your JavaScript before you instantiate your autocomplete object:
$.widget( 'ui.autocomplete', $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this;
$.ui.autocomplete.currentItems = items;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
}
});
$.ui.autocomplete.currentItems = [];
This will make it so whenever the menu appears, you have a list of current items the user can choose from stored in $.ui.autocomplete.currentItems. You can then use that to check against when you are submitting your form. Of course the way you implement this part is up to you depending on how dynamic your form is, but here is an example that requires hard-coding a list of input fields and making sure they all have ids.
//create an object that contains every input's id with a starting value of false
var inputs = {college: false};
//for each input, you will have a function that updates your 'inputs' object
//as long as all inputs have id's and they all are using autocomplete,
//the first line could be written as: $('input').change(function(){ and the
//function would only need to be written once. It is easier to maintain
//if you use seperate id's though like so:
$('#college').change(function(){
var id = this.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(this).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
});
//when you submit, check that your inputs are all marked as true
$('#submit').click(function(){
for(input in inputs){
if(inputs.hasOwnProperty(input) && inputs[input] == false){
return false; //one or more input does not have correct value
}
}
//all inputs have a value generated from search.php
$('#myform').submit();
});
UPDATE
The only difference between our two examples (one that works and one that doesn't) is that you are binding other events to your input element, onclick and onblur. So by changing our listener from change to blur as well mostly fixes the problem. But it creates a new problem when the enter/return key is pressed to submit the form. So if we add a listener for that specific event then everything works out ok. Here is what the code looks like now:
var validateInfo = function(elem){
var id = elem.id;
inputs[id] = false;
var length = $.ui.autocomplete.currentItems.length;
for(var i=0; i<length; i++){
if($(elem).val() == $.ui.autocomplete.currentItems[i].value){
inputs[id] = true;
}
}
}
$('#college').on('blur', function(){
validateInfo(this);
}).on('keydown', function(e){
if(e.which == 13){ //Enter key pressed
validateInfo(this);
}
});
Add a hidden input element to your form:
<input type="hidden" name="selectedvalue" id="selectedvalue" />
Add a select event handler to your autocomplete, that copies the selected value to the hidden input:
$("#college").autocomplete({
source: "search.php",
minLength: 5,
select: function (event, ui) {
$('#selectedvalue').val(ui.item.value);
}
});
Then just ignore the auto-complete form input in posted data.
As this is javascript, your only concern should be if an item is selected from the autocomplete list. This can simply be done by setting a variable to true on select and false on change. That is enough to prevent regular users from continuing without selecting a school. To prevent abuse you need to check the value server side after posting. All normal user will pass that check.
If I understand the question correctly, this is something I have encountered before. Here is some code pretty much lifted straight out of another project. I have used a local datasource here but the project this is lifted from uses remote data so there won't be a difference:
var valueSelected = '';
$('#college').autocomplete({
source: ['collegeA', 'collegeB', 'collegeC']
}).on('autocompletechange autocompleteselect', function (event, ui) {
if (!ui.item) {
valueSelected = '';
} else {
$('#submit').prop('disabled', false);
valueSelected = ui.item.label;
}
}).on('propertychange input keyup cut paste', function () {
if ($(this).val() != valueSelected) {
valueSelected = '';
}
$('#submit').prop('disabled', !valueSelected);
});
This will programatically enable and disable the submit button depending on whether a value has been selected by the user.
Fiddle here
I want to validate Checkbox in javascript, checkboxes is generating dynamically by PHP and name of checkboxes are like "checkbox1" , "checkbox2" ,"checkbox3" i.e. incrementing i++ and these numbers are coming from database, it might be first time only 2 rows fetched and next time 112 rows.
How i can make sure in javascript that atleast one checkbox must be selected.
// When you use jQuery... somehow like this
$('form').submit(function() {
if ($("input:checked").length == 0) {
alert('Please check at least one checkbox!');
return false;
}
});
If you do not want to use any js framework, then just give the same name attribute to the checkboxes
Assuming your checkboxes are named test
var chkBoxes = document.getElementsByName("test");
var chked=0;
for(var i=0;i<chkBoxes.length;i++)
{
if(chkBoxes[i].checked)
chked++;
}
if(chked===0)
alert("Please select a value");
Added as per the sample code specified in the comment
function isChecked()
{
var i=1;
var chkd=0;
var elem = "";
var chkForMoreChkBoxes=true;
do{
elem=document.getElementById("check_"+i);
try{
if(elem.checked)
{
chkd++;
}
i++;
}
catch(err)
{
chkForMoreChkBoxes=false;
}
}while(chkForMoreChkBoxes)
if(chkd===0)
{
alert("Please select a value");
return false;
}
}
Hay guys, I'm doing some work where i have a large collection of forms. Seems these aren't 'posted' the traditional way (i.e using a submit button). I need a way to collect all the names and values of all form data when clicking a link (document.location is then used for redirects).
I want names to stay intact so that i can used a simple PHP script to work with the data.
any suggestions?
Might I suggest Serialize Form to JSON:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and then you can do:
var formArray = $("#myform").serializeObject();
$.fn.valuesArr = function()
{
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
USE:
var myArr = $('input', $parentJQelem).valuesArr();
You could use something like my submit helper as a base
function submit(form) {
var form = $(form);
$.ajax(
{ data: $.param( form.serializeArray()),
dataType:'script',
type:'post',
url: form.attr("action")});
}
instead of a 'serializeArray()' i would use 'serialize()' and instead of posting it using ajax you could do whatever you want.
Sorry, dont have more time right now, but hopefully this snippet helps you.
cletus's answer is the best one in terms of efficency.
This is however another working solution that does not rely on JSON:
//this is my object I will fill my array with
function myObject(name, value)
{
this.name = name;
this.value = value;
}
var arr = $.map(
$('span'), function (item) {
var $item = $(item); //no need to $(item) 2 times
return new
myObject(
$item.attr("name"), //name field
$item.text() //value field
);
}
);
arr will be an array of myObject, each of them containing a name property and a value property.
Use your selector instead of $('span').
but all this functions dont work witch array names in inputs.
example -
this is correct for submit post form but when serialize i get
form[type[]]:2
this is not correct - i need - form[type][]:2