Help using JS dropdown for country/state with PHP - php

Here's the issue: I have a JS dropdown for country and state that runs in a PHP form for users to update their profiles.
The user selects country for ex 'USA', then state 'Colorado', and submits. What happens is that these values are saved OK on my database, but when the page refreshes, only the country dropdown remains selected with the user's choice. The state shows as 'Select State', although the value 'Colorado' is in the DB.
I just can't manage to have PHP and JS talk to each other so that if the user chose Colorado, it should be pulled from the DB and shown as selected whenever they refresh or come back to the page.
Any ideas how to do this? I tried the suggestion at the top of the JS code but was unsuccessful.
Here is the JS (some code trimmed for brevity):
// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = '';
var postCountry = '';
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:Alaska:Alaska|\
US:Alabama:Alabama|\
';
var country = '\
US:United States|\
CA:Canada|\
';
function TrimString(sInString) {
if ( sInString ) {
sInString = sInString.replace( /^\s+/g, "" );// strip leading
return sInString.replace( /\s+$/g, "" );// strip trailing
}
}
// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
if ( postCountry != '' ) {
defaultCountry = postCountry;
}
var countryLineArray = country.split('|'); // Split into lines
var selObj = document.getElementById('countrySelect');
selObj.options[0] = new Option('Select Country','');
selObj.selectedIndex = 0;
for (var loop = 0; loop < countryLineArray.length; loop++) {
lineArray = countryLineArray[loop].split(':');
countryCode = TrimString(lineArray[0]);
countryName = TrimString(lineArray[1]);
if ( countryCode != '' ) {
selObj.options[loop + 1] = new Option(countryName, countryCode);
}
if ( defaultCountry == countryCode ) {
selObj.selectedIndex = loop + 1;
}
}
}
function populateState() {
var selObj = document.getElementById('stateSelect');
var foundState = false;
// Empty options just in case new drop down is shorter
if ( selObj.type == 'select-one' ) {
for (var i = 0; i < selObj.options.length; i++) {
selObj.options[i] = null;
}
selObj.options.length=null;
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
// Populate the drop down with states from the selected country
var stateLineArray = state.split("|"); // Split into lines
var optionCntr = 1;
for (var loop = 0; loop < stateLineArray.length; loop++) {
lineArray = stateLineArray[loop].split(":");
countryCode = TrimString(lineArray[0]);
stateCode = TrimString(lineArray[1]);
stateName = TrimString(lineArray[2]);
if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
// If it's a input element, change it to a select
if ( selObj.type == 'text' ) {
parentObj = document.getElementById('stateSelect').parentNode;
parentObj.removeChild(selObj);
var inputSel = document.createElement("SELECT");
inputSel.setAttribute("name","state");
inputSel.setAttribute("id","stateSelect");
parentObj.appendChild(inputSel) ;
selObj = document.getElementById('stateSelect');
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
if ( stateCode != '' ) {
selObj.options[optionCntr] = new Option(stateName, stateCode);
}
// See if it's selected from a previous post
if ( stateCode == postState && countryCode == postCountry ) {
selObj.selectedIndex = optionCntr;
}
foundState = true;
optionCntr++
}
}
// If the country has no states, change the select to a text box
if ( ! foundState ) {
parentObj = document.getElementById('stateSelect').parentNode;
parentObj.removeChild(selObj);
// Create the Input Field
var inputEl = document.createElement("INPUT");
inputEl.setAttribute("id", "stateSelect");
inputEl.setAttribute("type", "text");
inputEl.setAttribute("name", "state");
inputEl.setAttribute("size", 30);
inputEl.setAttribute("value", postState);
parentObj.appendChild(inputEl) ;
}
}
function initCountry(country) {
populateCountry(country);
populateState();
}
and here is the PHP/HTML (trimmed a bit):
<?php
include 'dbc.php';
page_protect();
$err = array();
$msg = array();
if ($_POST['doUpdate'] == 'Update') {
foreach ($_POST as $key => $value) {
$data[$key] = filter($value);
}
$country = $data['country'];
$state = $data['state'];
mysql_query("UPDATE users SET
`country` = '$data[country]',
`state` = '$data[state]'
WHERE id='$_SESSION[user_id]'
") or die(mysql_error());
$msg[] = "Your Profile has been updated";
//header("Location: mysettings.php?msg=Your new password is updated");
}
$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
?>
<html>
<body>
<form name="profile_form" id="profile_form" method="post" action="">
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
<input name="doUpdate" type="submit" id="doUpdate" value="Update">
<table>
<tr>
<th>Country:</th>
<td><select id='countrySelect' name='country' onchange='populateState()'>
</select></td>
</tr>
<tr>
<th>State:</th>
<td>
<select id='stateSelect' name='state'>
</select>
<script type="text/javascript">
initCountry('<?php echo $row_settings['country']; ?>');
</script>
</td>
</tr>
</table>
</form>
</body>
</html>

One of the issues i often run into with Javascript is the load order.
You appear to be running and calling populateCountry and populateState at the same time, thereby not having much opportunity for the State list to be populated once the country list has been determined.
Consider moving "populateState()" to the last line of "populateCountry()" so it calls it at the end of the function processing.
There are multiple ways to do this, but this is the simplest to illustrate the point.

Change the top lines
// If you have PHP you can set the post values like this
//var postState = '<?php echo $_POST["state"] ?>';
//var postCountry = '<?php echo $_POST["country"] ?>';
var postState = '';
var postCountry = '';
to
// If you have PHP you can set the post values like this
var postState = '<?= $_POST["state"] ?>';
var postCountry = '<?= $_POST["country"] ?>';
//var postState = '';
//var postCountry = '';
Does that not work?
PHP Short tags, ie "<?=" are not enabled by default anymore i believe in some of the newer php versions. I've stopped using it, i know it looks pretty but it can be a pain if you migrate to a server that doesn't support them.

Related

Get Value of Appended Element After Submit Button with POST Type Form

I want to get the value of appended elements after submitting. It appends the right name attributes, but I can't get the value
<script>
<?php
$options = '';
while($searched_species_adding = mysqli_fetch_array($search_species_adding)){
$name = $searched_species_adding['name'];
$options = $options.'<option>'.$name.'</option>';
}
echo 'var options = "'.$options.'";';
?>
var count=2;
$( "#add-species" ).click(function() {
var html=$("<tr id='species-"+count+"'><td><select name='species-"+count+"' class='form-control'>"+options+"</select></td><td><input id='species-num-"+count+"' name='species-num-"+count+"' class='form-control' type='number'></td></tr>");
$("#species-container").append(html);
$("#species-num-"+count).prop('required',true);
count++;
var wew = ($('tr', $("#wew").find('tbody')).length);
$(".tr-num").remove();
$("#species-container").append("<input class='tr-num' type='hidden' value='"+wew+"' name='tr_count'>");
$(".tr-num").val(wew);
});
$( "#remove-species" ).click(function() {
count--;
$("#species-"+count).remove();
var wew = ($('tr', $("#wew").find('tbody')).length);
$(".tr-num").val(wew);
});
</script>
Above is the script for appending.
And here is my code in getting the values in a form after submitting:
if(isset($_POST['add-delivered'])){
$requestor = $_POST['requestor'];
$org_office = $_POST['org_office'];
$address = $_POST['address'];
$date_pickup = $_POST['date_pickup'];
$location = $_POST['location'];
$planting_type = $_POST['planting_type'];
$tr_count = $_POST['tr_count'];
$species = '';
for($x = 1; $x <= $tr_count; $x++){
$species = $species.$_POST['species-'.$x];
}
echo '<script>alert("'.$tr_count.'")</script>';
exit();
}

How to store ajax value in php variable?

I want to store ajax value 'when selected' stored in php variable.
<select name="client_name" onchange="ajaxReq('product_name', this.value);">
<option>- - -</option>
<option value="SANY">SANY</option>
<option value="MBFC">MBFC</option>
</select>
<span id="slo_product_name"> </span>
<span id="slo_release_no"> </span>
<script type="text/javascript">
var ar_cols = ["client_name","product_name","release_no",null]; var preid = "slo_";
</script>
I've tried this, but didn't succeeded.
$releasenu=$_POST['release_no'];
How should i store the ajax value of release_no in php variable? Is there any other way?
function ajaxReq(col, wval) {
removeLists(col);
if(wval!='- - -' && wval!='') {
var request = get_XmlHttp();
var php_file = 'select_list.php';
var data_send = 'col='+col+'&wval='+wval;
request.open("POST", php_file, true);
document.getElementById(preid+col).innerHTML = 'Loadding...';
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);
request.onreadystatechange = function() {
if (request.readyState==4) {
document.getElementById(preid+col).innerHTML = request.responseText; }
} } }
According to your code, you should use this in your select_list.php script:
$col = $_POST['col'];
$wval = $_POST['wval'];
// now you can use those variables to save to DB, or get some data out of DB
I assume you want to have cascade <select> elements, you should change your ajaxReq() function:
function ajaxReq(col, wval) {
// first remove all selects that are after this one
var remove = false;
var next = null; // we also need to trap next select so we can fill it
for (i in ar_cols) {
if (ar_cols[i] == col) {
remove = true; // from now on, remove lists
} else if (remove) { // if ok to remove
if (!next) {
next = ar_cols[i]; // now we found next column to fill
}
if (ar_cols[i]) { // remove only non null
removeLists(ar_cols[i]);
}
}
}
if(wval!='- - -' && wval!='' && next) { // also if there is column after to fill
var request = get_XmlHttp();
var php_file = 'select_list.php';
var data_send = 'col='+col+'&wval='+wval+'&next='+next; // also add next param
request.open("POST", php_file, true);
document.getElementById(preid+col).innerHTML = 'Loadding...';
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);
request.onreadystatechange = function() {
if (request.readyState==4) {
// we fill next select
document.getElementById(preid+next).innerHTML = request.responseText;
}
}
}
}
Your select_list.php should look something like this:
$col = $_POST['col']; // this is just a filter for values in next <select>
$wval = $_POST['wval'];
$next = $_POST['next']; // we need to get this param or we cannot setup next <select>
// using $col and $wval variables get values from DB
echo '<select name="' . $next . '" onchange="ajaxReq(\'' . $next . '\', this.value);">';
foreach ($data as $row) {
echo '<option ...>...</option>'; // fix this to work for you
}
echo '</select>';
// Code changed due to bug found
The ajax request should contain one more parameter (next column) since the returned <select> should have name and onchange event prepared for next, not the currently changed.
Check the code above again.

I can not take all the arrays for serialize jquery

I have a page that has three checkbox lists, the three are dynamically generated
what I want and that as the User is clicking the checkbox values ​​are passed via post, but I only managed to catch Esto values ​​of the first list
I did the code like this:
$("body").find(".fcID").click(function(){
// var v = $(this).val();
//alert(v);
var form = jQuery('#form');
valor = form.serialize();
$.ajax({
type : "POST",
url:"biblioteca/filtra.php",
data: valor,
success: function(data){
$("#tabelafiltro").html(data);
}
});
in html, I put a form with the id of her form and name the form
within that form, I have the checkboxes, so:
<form name="form" id="form" action="" method="post">
<table>
<tr>
<td><input type="checkbox" class="fcID" value="<?php echo $linha['fm-cod-com'] ?>" name="fcID[]"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="checkbox" class="fcID" name="fam[]" value="<?php echo $linha['fm-codigo'] ?>" /></td>
</tr>
</table>
</form>
and the php:
$id = $_POST['fcID'];
$fam = $_POST['fam'];
echo(count($fam)) . " + " . count($id);
somebody help me?
Your code is correct, are u sure that the fam[] checkboxes are checked? Checkboxes will serialize only if they have atribute checked="checked".
Unfortunately the "name" is not converted to an array by jQuery.. so instead of this:
echo $_POST['fcID'][0]; // undefined
you have this
echo $_POST['fcID[]']; // expected value
I created the following. It has some limitations, but should do what you want. I appreciate if you can rate my answer.
var form = jQuery('#form');
valor = form.formToObj();
// formToObj (c) 2012 Frank Forte.
// Please contact me for a free license to use on personal or business website
// #frankforte or frank # interactinet .com!
jQuery.fn.formToObj = function()
{
var obj = {}
jQuery("input,select,textarea",this).each(function(){
if(jQuery(this).attr("disabled")){
return;
}
var n = jQuery(this).attr("name") || jQuery(this).attr("id")
var v = jQuery(this).val();
// e.g.<input name="test[one][two][three]" value="hello world">
if(!n.match(/\[/))
{
obj[n] = v
}
else
{
// get keys of array, e.g. "one","two","three"
var keys = []
nkeys= n.split('[')
var i = 0;
for(k in nkeys)
{
if(i > 0)
{
var nk = nkeys[k]
if(typeof nk == "string")
{
if(nk.match(/\]/))
{
nk = nk.replace("]","")
}
keys.push(nk);
}
}
i++
}
// name e.g. "test"
n = n.replace(/^([^\[\]]+)\[.*$/i,"$1");
// create object and add value then array keys from bottom up
var iobj = {}
for(i = keys.length; i > 0; i--)
{
j = i-1;
var k = keys[j]
if(k==""){k = 0;}
if(i == keys.length)
{
iobj[k] = v
}
else
{
iobj[k] = iobj
}
}
// Need to start with obj[n] and add new values under appropriate keys
// prevents unsetting or overwriting keys deeper than n
if(typeof obj[n] == "undefined")
{
obj[n] = {}
}
obj[n][k] = iobj[k]
}
})
return obj
}

Passing js variables to php using jquery

I'm trying to do a realllly simple post of a javascript variable to a php file.
Jquery bit in keyinput.php:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
PHP bit in viewcomic.php:
include './scripts/keyinput.php';
$JSIndex = $_POST['variable'];
echo "Index = " . $JSIndex;
//$JSIndex should be equal to the javascript variable imgIndex... but it outputs nothing
Any thoughts would be extremely helpful! I'm trying to get my comics website to go live.
Thanks!
Your logic is wrong: at the moment you define your key variable, e is undefined. Then you attach your event handler inside an if statement that will always evaluate to false so that will never work.
The assignment to key should be inside your event handler and the conditional needs to go, you already have that inside your event handler.
Edit: you should also only do your ajax call if one of your action keys is pressed (put it inside the event handler) and do something with the result.
Edit 2: Checkout the manual on $.post, you should add a callback function to process the return value of your php script.
For example:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);

delete link with js confirm + php

this was the delete link
<div class="artworkdelete">
Delete
</div>
apparently, when that link is clicked, the portal deletes the data automatically, i think it's an ajax thing because the page doesn't refresh. so i was ask to add a confirm pop up to ask the user to click yes or no if he wants to delete the data or not, and within the confirm box , it should mention the name of the data to be deleted like e.g
"are you sure you want to delete row_title ?"
here's the function of the deleteThisArtWork()
function deleteThisArtWork(artwork_id){
var artwork_id = artwork_id.split('_');
var cat_id=artwork_id[2];
artwork_id = artwork_id[1];
//$('#divStatus').html('processing request, please wait');
//$(".pleaseWait").dialog("open");
openLightBox();
$.ajax({
type: 'POST',
url: '<?php echo BASE_URL;?>ajax/ajax_methods_gallery.php',
data: 'deleteartwork=yes&artwork_id='+artwork_id+'&category_id='+cat_id,
success: function(msg){
//alert(msg);
msg = 'done';
var status=msg;
var deleted='';
if(status == 'done') {
var temp_lid = 'li_'+artwork_id+'_'+cat_id+'_';
//alert(counter);
for(var v=1;v<counter;v++){
var curid = tempIdArr[v];
curid = curid.split('#');
var curlid = curid[0];
if(temp_lid == curlid){
var del_aw_pos = curid[1];
break;
}
}
del_aw = temp_lid+'#'+del_aw_pos;
var i = 1;
var j =0;
var op = false;
var delpoint;
var endpoint;
var delcatid = '';
var artcounter = 0;
var artcounterArr = new Array();
$(".sortli").each(function (){
var atid = this.id.split('_');
//if(atid[2]!=cat_id)return;
if(this.id == del_aw){
deleted = 'yes';
delcatid = atid[2];
$(this).remove();
op = true;
i=i+1;
delpoint=i-1;
//alert('D'+delpoint);
//return;
}
if(atid[2]==cat_id){endpoint = i-1;artcounter=artcounter+1;}
else if(j==0 && artcounter > 0){
if(artcounter>0)artcounter = artcounter-1;
//else artcounterArr[j] = 0;
artcounterArr[j] = artcounter;
j=j+1;
artcounter = 0;
}
i = i + 1;
});
//alert(delpoint)
//alert(endpoint);
//alert(artcounterArr[0]);
if(op){
for(var k=delpoint; k<counter-1;k++){
var orderVal1 = tempOrderArr[k];
if(k<endpoint)document.getElementById('sortvalid_'+(k+1)).innerHTML = orderVal1;
document.getElementById('sortvalid_'+(k+1)).id = 'sortvalid_'+(k);
document.getElementById('sortdn_'+(k+1)).id = 'sortdn_'+(k);
document.getElementById('sortup_'+(k+1)).id = 'sortup_'+(k);
var t = tempIdArr[(k+1)].split('#');
t=t[0];
document.getElementById(tempIdArr[(k+1)]).id = t+'#'+k;
}
$(".rowHead").each(function (){
var taid = this.id;
var sp = this.id.split("^");
var a1 = sp[1];
//alert(a1);
//alert(cat_id);
if(parseInt(a1)>parseInt(cat_id)){
var a2 = sp[2];
var ta = 'lititle^'+a1+'^';
//alert(ta);
document.getElementById(taid).id = ta+(a2-1);
}
});
var a2temp;
var a1temp;
var delcat=null;
var rowHeadLast;
$(".rowHead").each(function (){
//var taid = this.id;
rowHeadLast = this;
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(a2temp == a2 && delcat==null){delcat = a2temp; delcatid=a1temp;}
a2temp = a2;
a1temp = a1;
});
var delok = false;
$(".rowHead").each(function (){
//var taid = this.id;
//alert(deleted);
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(delcat == a2 && a1==delcatid && deleted==''){delok= true;deleted='yes';$(this).remove();}
});
//alert(delcatid);
//if(!artcounterArr[0])alert('d');
if(!delok){
$(".rowHead").each(function (){
var sp = this.id.split("^");
var cid_t = sp[1];
if(!artcounterArr[0] && delcatid == cid_t)$(this).remove();
//else if(artcounterArr[0]<=0)$(this).remove();
});
}
if(deleted ==''){
$(rowHeadLast).remove();
}
}
setDivsInArray();
//$(".pleaseWait").dialog("close");
closeLightBox();
}
else if(status == 'DBDelete:error'){
//$('#row_'+artwork_id).fadeOut(3500);
$('#divStatus').fadeIn(500);
$('#divStatus').html('<b>Artwork Delete Error</b>');
$('#divStatus').fadeOut(4500);
}
}
});
}
it's quite long , I think I don't need all of those stuff if the requirement is just delete the data when "Yes" was clicked from the confirm pop up box
now here's the delete PHP function
function deleteArtWork($artwork_id,$category_id){
$artwork_cat_lookup_del = "delete from artwork_category_lookup where artwork_id = '$artwork_id' AND category_id='$category_id'";
if(mysql_query($artwork_cat_lookup_del)){
$userObj = new User();
$allArtWorkByCat = $userObj->allArtWorkByCat($category_id);
for($itr = 0; $itr<count($allArtWorkByCat); $itr++){
$ordr = $itr + 1;
$art_id = $allArtWorkByCat[$itr]['artwork_id'];
$updateSQL = "update artwork_category_lookup set artwork_display_order='$ordr' where artwork_id = '$art_id' AND category_id = '$category_id'";
mysql_query($updateSQL);
}
$action = $userObj->userActions('Artwork id: '.$artwork_id.' is deleted', 'Gallery');
$userObj->setActionintoDB($action);
echo 'done';
}
else echo 'DBDelete:error';
return;
I don't think that you want to start changing that code above as that is used to pass the relevant data to the php script via ajax.
What you need is a javascript prompt to intercept the link click and give the user an option to continue or cancel the deletion action. Is this correct?
http://www.tizag.com/javascriptT/javascriptconfirm.php
At the start of the "deleteThisArtWork" javascript function you need to display a prompt.
function deleteThisArtWork(artwork_id){
var answer = confirm("Are you sure you want to delete this record?");
if (answer){
//do the rest of the function as usual, i.e. delete row via ajax.
}else{
return false;
}
}
That should stop the user from accidentally deleting a record without at least having to accidentally click on a confirmation popup as well!
If you want to make the text in the confirm popup dynamic, you would need to either pass in the dynamic text as a variable to the "deleteThisArtwork" method or draw it from another element on the page using some javascript.

Categories