php - Submit Form Data without Reloading page -


i know question has been asked , answered bunch of times life of me can not solution work on code. believe if redo code, work properly, , in retrospect time i've spent on issue should have redone code...but beyond deadline , have working prototype up...

can advise how update multiple forms on single page without reloading page? horrible @ php , complete noob js/jquery/ajax @ best. html/php in single file , believe causing me problems/is largest obstacle @ getting ajax form processing work.

basically, want users to:

  1. select teams multiple dropdowns in form group 1 (league champs) , on update update db newly selected team without reloadding page.

  2. edit team scores per match , on score submit/update, update db new scores.

for each requirement there multiple forms (1 each leagues, 1 each per match) have set class on each form id.

everything works via php, form submission reloads page each time submitted , not ideal.

i have tried ajax code here http://scotch.io/tutorials/javascript/submitting-ajax-forms-with-jquery numerous solutions no luck. don't know enough know how edit code work situation.

i'm not sure code answer code in single page , prob long copy/paste in post. provide info/data needs me this. i'm 7 weeks past delivery (it's personal project me , friends not big of deal...but want done this).

ok here code. it's awful, , in process of refactoring utilize functions , and better queries, etc. have , hoping make "work" before reworked it...(the sections wish update per question commented stackoverflow in comment). helps me, still @ impasse.

<?php // includes , session data here  // connect db  // current date , time $cur_time = date('y-m-d h:i:s'); require_once('current_week.php'); // file contains $cur_week , $cur_date vars  // grab match id each match use userpicks check/populate $query_matchids = "select id match_id matches order match_time"; $data_matchids = mysqli_query($dbc, $query_matchids) or die('error querying matches table match ids.'); $match_ids = array(); while ($row_matchids = mysqli_fetch_array($data_matchids)) { array_push($match_ids, $row_matchids['match_id']); }  // check if userpicks exist $query_userpicks = "select user_id userpicks_userid, match_id userpicks_matchid, team_id_winner userpicks_winnerid, " . "home_score userpicks_hscore, away_score userpicks_ascore " . "from user_picks " . "where user_id = $user_id"; $data_userpicks = mysqli_query($dbc, $query_userpicks)  or die('error querying user_picks table user picks data.'); if (mysqli_num_rows($data_userpicks) == 0) { // if no userpicks exist user, populate users picks' list null data each match foreach ($match_ids $match_id) { $query_userpicks_initial = "insert user_picks (user_id, match_id) " . "values ($user_id, $match_id)"; mysqli_query($dbc, $query_userpicks_initial)  or die('error querying user_picks table insert empty userpicks data.'); } } // if userpicks exist user, put data array used later $userpicks = array(); while ($row_userpicks = mysqli_fetch_assoc($data_userpicks)) { array_push($userpicks, $row_userpicks); }  // grab week data season_weeks table display matches , week views pagination $query_weeks = "select week_number week, start_date week_start, end_date week_end season_weeks order start_date"; $data_weeks = mysqli_query($dbc, $query_weeks) or die('error querying season_weeks table week data.'); $weeks = array(); while ($row_weeks = mysqli_fetch_assoc($data_weeks)) { array_push($weeks, $row_weeks); } // total number of weeks in season...this should total number of rows in season column...edit more accurate if not $num_weeks = mysqli_num_rows($data_weeks);  // grab league data $query_leagues = "select * leagues"; $data_leagues = mysqli_query($dbc, $query_leagues) or die('error querying leagues table.'); $leagues = array(); while ($row_leagues = mysqli_fetch_assoc($data_leagues)) { array_push($leagues, $row_leagues); }  // grab match , results data generate matches , results $query_matches = "select m.id, m.match_time, m.home_team_id, m.away_team_id, m.league_id, " . "l.name league_name, l.league_abbr, l.start_date league_start, l.end_date league_end, l.img_lrg league_crestlg, l.img_icon league_crestsm, " . "h.name home_team, h.team_abbr home_abbr, h.stadium, h.img_lrg home_crestlg, h.img_icon home_crestsm, h.website home_url, " . "a.name away_team, a.team_abbr away_abbr, a.img_lrg away_crestlg, a.img_icon away_crestsm, a.website away_url, " . "mr.result_home, mr.home_score, mr.result_away, mr.away_score, mr.pks, mr.pks_home, mr.pks_away, " . "up.match_id user_matchid, up.team_id_winner user_winnerid, up.home_score user_hscore, up.away_score user_ascore " . "from matches m " . "join leagues l " . "on m.league_id = l.id " . "join teams h " . "on m.home_team_id = h.id " . "join teams " . "on m.away_team_id = a.id " . "left join match_results mr " . "on m.id = mr.match_id " . "left join user_picks " . "on m.id = up.match_id , up.user_id = '$user_id' " . "order league_id, match_time"; $data_matches = mysqli_query($dbc, $query_matches)  or die('error querying matches, teams, , match_results tables match data.'); $matches = array(); while ($row_matches = mysqli_fetch_assoc($data_matches)) { array_push($matches, $row_matches); }  // grab points data ace_points   ?> <section class="container"> <div class="row"> <h1 class="text-center col-xs-12"><?php echo $page_main_header; ?></h1> </div>  <div class="row"> <div class="col-xs-12"> <div class="container champions_container"> <div class="row"> <button type="button" id="league_champs_button" class="btn btn-primary btn-lg col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2 col-xs-12" data-toggle="collapse" data-target="#champs_selections_container">select league champions</button> </div> <div class="row"> <div id="champs_selections_container" class="collapse"> <?php // grab champions pick data each league per user foreach ($leagues $league) { // grab teams league $query_teams = "select id, name teams league_id = '" . $league['id'] . "'"; $data_teams = mysqli_query($dbc, $query_teams)  or die('error querying teams table team data.'); $teams = array(); while ($row_teams = mysqli_fetch_assoc($data_teams)) { array_push($teams, $row_teams); } // check champion picks see if champion has been selected $query_champions = "select league_id, team_id, pts_value champ_picks user_id = $user_id , league_id = '" . $league['id'] . "'"; $data_champions = mysqli_query($dbc, $query_champions) or die('error querying champ_picks table chamions data.'); $champions = array(); while ($row_champions = mysqli_fetch_assoc($data_champions)) { array_push($champions, $row_champions); } $champ_points = ($champ_orig_points - ($cur_week * 2)); // if champion exists in user's champ_picks, set variables accordingly if (mysqli_num_rows($data_champions) == 1) { $user_champ = $champions[0]['team_id']; if ($champions[0]['pts_value'] === null) { $user_champ_pts = 0; } else { $user_champ_pts = $champions[0]['pts_value']; }  } else { // no champion selected league yet $user_champ = ''; $user_champ_pts = 0; }  // todo: if champ picks change, update edited selections - via ajax /* stackoverflow - champions */ // if user submits form update champ_picks table new champion selection(s) if (isset($_post['champs_submit_league' . $league['id']])) { $league_id = $_post['leagueid'][0]; $updated_champs = $_post['champions'][0]; $updated_champs_pts = $champ_points; $query_champs_update = "update champ_picks set team_id = '$updated_champs', pts_value = '$updated_champs_pts' league_id = '$league_id'"; mysqli_query($dbc, $query_champs_update) or die('error querying champs_picks update champions ' . $league['name'] . '.'); } else { //echo 'post not set champions ' . $league['id'] . '<br />'; } ?> <form method="post" action="<?php $_server['php_self']; ?>" id="champ_picks_league<?php echo $league['id']; ?>" class="col-xs-12"> <div class="form-group col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2 col-xs-12"> <label class="sr-only" for="mousetrap_champs<?php echo $league['id']; ?>">leave blank <span class="required">(required prove human)</span></label> <input class="sr-only form-control" type="text" id="mouestrap_champs<?php echo $league['id']; ?>" name="mousetrap_champs<?php echo $league['id']; ?>" value="<?php if(!empty($spam_protect)) echo $spam_protect; ?>" placeholder="leave blank" /> </div> <div class="form-group col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2 col-xs-12"> <input type="hidden" id="leagueid<?php echo $league['id']; ?>" name="leagueid[]" value="<?php echo $league['id']; ?>" /> <label class="sr-only" for="champions"><?php echo $league['name']; ?> champs</label> <div class="input-group" style="position: relative;"> <select class="form-control" id="champions<?php echo $league['id']?>" name="champions[]"> <?php echo 'champs: ' . $user_champ; ?> <option value="" <?php if (empty($user_champ)) echo 'selected="selected"'; ?>><?php echo $league['name']; ?> champs</option> <?php foreach ($teams $team) { // fixit: if post set per league pick, show newly updated champion team selection -current code isnt working //  if (isset($_post) && $updated_champs == $team['id']) { //      $select_option = 'selected="selected"'; //      echo '<option value="' . $team['id'] . '" ' . $select_option . '>' . $team['name'] . ' (current pick)</option>'; //  } if (!empty($user_champ) && $user_champ == $team['id']) { $select_option = 'selected="selected"'; echo '<option class="current_userpick" value="' . $team['id'] . '" ' . $select_option . '>' . $team['name'] . ' (current pick)</option>'; } else { $select_option = ''; echo '<option value="' . $team['id'] . '" ' . $select_option . '>' . $team['name'] . '</option>'; }                                            } ?> </select> <span class="input-group-addon champ_points_display"><?php echo $champ_points; ?> (<?php echo $user_champ_pts; ?>)</span> <?php  // show update button if user has agreed rules if ($_session['user_rules'] == 'y') { ?> <input type="submit" id="champs_submit_league<?php echo $league['id']; ?>" class="btn btn-primary btn-lrg btn-block form-control input-group-addon" name="champs_submit_league<?php echo $league['id']; ?>" value="update" /> <?php } ?> <!-- todo: move seperate file, disable update button if user re-selects original userpick champ --> <script type="text/javascript"> $(document).ready(function() { $("#league_champs_button").click(function() { $("input#champs_submit_league<?php echo $league['id']; ?>").css("display", "none"); }); $("#champions<?php echo $league['id']?>").change(function() { $("input#champs_submit_league<?php echo $league['id']; ?>").fadein(1000); }); }); </script> </div> </div> </form> <?php } ?> </div> </div> </div> <!-- week pagination - show if have more 1 week of matches--> <?php  if ($num_weeks > 1) { ?> <div class="container"> <div class="row"> <div class="col-xs-12 text-center"> <ul class="pagination"> <!-- pagination goes here --> </ul> </div> </div> </div> <?php } // loop through each week of season(s) foreach ($weeks $week) { if (isset($_get['week']) && $_get['week'] == $week['week']) { ?> <div class="container week_container"> <div class="col-xs-12"> <div class="row week_heading"> <h3 class="col-xs-12">week <?php echo $week['week']; ?></h3> <p class="col-xs-12"><?php echo date("f j", strtotime($week['week_start'])) . ' - ' . date("f j, y", strtotime($week['week_end'])); ?></p> </div>  <?php // loop through each league foreach ($leagues $league) { $league_id = $league['id']; $league_name = $league['name']; $league_abbr = $league['league_abbr']; $league_start = $league['start_date']; $league_end = $league['end_date']; $league_crestlg = $league['img_lrg']; $league_crestsm = $league['img_icon']; $league_img_dir = ace_image_uploadpath . strtolower(str_replace(' ', '_', $league['name'])) . '/'; // make sure matches exist given league , given week...only display leagues matches week $query_league_matches = "select id matches league_id = '$league_id' , date(match_time) >= '" . $week['week_start'] . "' , date(match_time) <= '" . $week['week_end'] . "'"; $result_league_matches = mysqli_query($dbc, $query_league_matches)  or die('error querying matches number of league matches in given week.'); if (mysqli_num_rows($result_league_matches) > 0) { ?> <div class="row league_container"> <div class="row"> <div class="panel-group" id="accordion_league<?php echo $league_id; ?>"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"><a data-toggle="collapse" data-parent="#accordion_league<?php echo $league_id; ?>" href="#collapse_league<?php echo $league_id; ?>"><?php echo $league_name; ?> matches</a></h4> </div> <div id="collapse_league<?php echo $league_id; ?>" class="panel-collapse collapse"> <div class="panel-body"> <?php // create match variables foreach ($matches $match) { $match_id = $match['id']; $match_time = $match['match_time']; $match_date = date('y-m-d', strtotime($match_time)); // use grabbing matches given week $match_time_convert = strtotime($match_time); // convert user input time unix timestamp can convert diff format display $match_time_readable = date('g:ia', $match_time_convert); $match_date_readable = date('l f j, y', $match_time_convert); $match_leagueid = $match['league_id']; $league_name = $match['league_name']; $home_team = $match['home_team']; $home_abbr = $match['home_abbr']; $home_id = $match['home_team_id']; $home_crestlg = $match['home_crestlg']; $home_crestsm = $match['home_crestsm']; $home_url = $match['home_url']; $stadium = $match['stadium']; $away_team = $match['away_team']; $away_abbr = $match['away_abbr']; $away_id = $match['away_team_id']; $away_crestlg = $match['away_crestlg']; $away_crestsm = $match['away_crestsm']; $away_url = $match['away_url']; $result_home = $match['result_home']; $result_away = $match['result_away']; $score_home = $match['home_score']; $score_away = $match['away_score']; $pks = $match['pks']; $pks_home = $match['pks_home']; $pks_away = $match['pks_away']; $user_match_id = $match['user_matchid']; $user_winner_id = $match['user_winnerid']; $user_score_home = $match['user_hscore']; $user_score_away = $match['user_ascore']; // set winner variable if ($result_home == 'w') { // home team win $winner = $home_team; $winner_id = $home_id; } elseif ($result_away == 'w') { // away team win $winner = $away_team; $winner_id = $away_id; } else { // draw $winner = ''; $winner_id = ''; } // todo: if match scores change, update edited selections - via ajax /* stackoverflow - match score updates */ // if user edits match scores update userpicks table new scores , winner picks if (isset($_post['picks_submit' . $match_id])) { $picks_matchid = $_post['picks_matchids'][$match_id]; $picks_hscore = $_post['home_scores'][$match_id]; $picks_homeid = $_post['home_ids'][$match_id]; $picks_ascore = $_post['away_scores'][$match_id]; $picks_awayid = $_post['away_ids'][$match_id]; if ((!empty($picks_hscore)) && (!empty($picks_ascore))) { // set winner variable if ($picks_hscore > $picks_ascore) { // home team win $picks_winnerid = $picks_homeid; } elseif ($picks_ascore > $picks_hscore) { // away team win $picks_winnerid = $picks_awayid; } else { // draw $picks_winner = 'draw'; $picks_winnerid = '-1'; } $query_score_update = "update user_picks " . "set team_id_winner = '$picks_winnerid', home_score = '$picks_hscore', away_score = '$picks_ascore' " . "where user_id = '$user_id' , match_id = '$picks_matchid'"; mysqli_query($dbc, $query_score_update) or die('error querying user_picks update scores match #' . $match_id . '.'); } elseif ((empty($picks_hscore)) && (!empty($picks_ascore))) { // if home score empty // todo: echo errors missing score data } else { // if away score empty // todo: echo errors missing score data } } //else { // need if post not set? //} // display week's matches if (($match_leagueid == $league_id) && ($match_date >= $week['week_start']) && ($match_date <= $week['week_end'])) { if (($cur_time > $match_time)) { echo '<div class="row match_container past_match">'; } else { echo '<div class="row match_container">'; } ?> <ul class="match_info col-md-2 col-xs-12"> <li class="match_date"><span class="label">date</span><?php echo date("d. m. j", strtotime($match_time)); ?></li> <li class="match_time"><span class="label">kickoff</span><?php echo date("g:ia", strtotime($match_time)); ?></li> <li class="stadium"><span class="label">stadium</span><?php echo $stadium; ?></li> <li class="league_logo"><span class="label">league</span> <?php if (!empty($league_crestsm)) { echo '<img src="' . $league_img_dir . 'crests/' . $league_crestsm . '" alt="' . $league_name . ' logo" title="this ' . $league_name . ' match." /></li>'; } else { echo $league_name; } ?> </li> </ul> <form method="post" action="<?php $_server['php_self']; ?>" id="form_match<?php echo $match_id; ?>" class="teams_container col-md-8 col-xs-12"> <input type="hidden" min="0" class="form-control" id="picks_matchid_<?php echo $match_id; ?>" name="<?php echo 'picks_matchids[' . $match_id . ']'; ?>" value="<?php echo $match_id; ?>" /> <?php                                               // if results exist match, display them  // if no results exist match else { ?> <div> <div class="home_team col-xs-5"> <div class="row"> <h4 class="col-xs-12 team_name"><?php echo $home_team; ?></h4> <h4 class="col-xs-12 team_name team_abbreviation"><a href="<?php echo $home_url; ?>" rel="" title="visit <?php echo $home_team; ?>'s website."><?php echo $home_abbr; ?></a></h4> <p class="col-xs-12 team_url"><a href="<?php echo $home_url; ?>" rel="" title="visit <?php echo $home_team; ?>'s website."><?php echo $home_url; ?></a></p> </div> <div class="row"> <img class="team_crest col-xs-6" src="<?php echo $league_img_dir; ?>crests/<?php echo $home_crestsm; ?>" alt="<?php echo $home_team; ?>'s crest" /> <div class="form-group home_score score col-xs-6"> <input type="hidden" class="form-control" id="homeid_<?php echo $home_id; ?>" name="<?php echo 'home_ids[' . $match_id . ']'; ?>" value="<?php echo $home_id; ?>" /> <label class="sr-only" for="home_score">home score</label> <?php // if current time before match time, allow user pick match results if ($cur_time < $match_time) { if ((!empty($user_score_home) || ($user_score_home === 0)) && ($_session['user_rules'] == 'y')) { ?>       <!-- stackoverflow - match score updates --> <input type="number" min="0" class="form-control" id="home_score_<?php echo $match_id; ?>" name="<?php echo 'home_scores[' . $match_id . ']'; ?>" value="<?php echo $user_score_home; ?>" />  <?php } // if user has not yet agreed rules, not allow user pick match results elseif ((!empty($user_score_home) || ($user_score_home === 0)) && ($_session['user_rules'] == 'n')) { ?>  <input type="number" min="0" disabled="disabled" class="form-control" id="home_score_<?php echo $match_id; ?>" name="<?php echo 'home_scores[' . $match_id . ']'; ?>" value="<?php echo $_post['home_scores'][$match_id]; ?>" /> <?php } else { ?> <input type="number" min="0" class="form-control" id="home_score_<?php echo $match_id; ?>" name="<?php echo 'home_scores[' . $match_id . ']'; ?>" value="<?php echo $_post['home_scores'][$match_id]; ?>" /> <?php            } } // if current time after match time , match over, not allow user pick match results elseif ($cur_time >= date('y-m-d h:i', (strtotime('+95 minutes', strtotime($match_time))))) { ?> <input type="number" min="0" disabled="disabled" class="form-control" id="home_score_<?php echo $match_id; ?>" name="<?php echo 'home_scores[' . $match_id . ']'; ?>" value="<?php echo $user_score_home; ?>" /> <p class="alert-danger post_match_warning">results pending.</p> <?php } // if current time after match time match still playing, not allow user pick match results else { ?> <input type="number" min="0" disabled="disabled" class="form-control" id="home_score_<?php echo $match_id; ?>" name="<?php echo 'home_scores[' . $match_id . ']'; ?>" value="<?php echo $user_score_home; ?>" /> <p class="alert-danger post_match_warning">too late.</p> <?php  } ?> </div> </div> </div> <p class="versus_text col-xs-2">vs</p> <div class="away_team col-xs-5"> <div class="row"> <h4 class="col-xs-12 team_name"><?php echo $away_team; ?></h4> <h4 class="col-xs-12 team_name team_abbreviation"><a href="<?php echo $away_url; ?>" rel="" title="visit <?php echo $away_team; ?>'s website."><?php echo $away_abbr; ?></a></h4> <p class="col-xs-12 team_url"><a href="<?php echo $away_url; ?>" rel="" title="visit <?php echo $away_team; ?>'s website."><?php echo $away_url; ?></a></p> </div> <div class="row"> <img class="team_crest col-xs-6" src="<?php echo $league_img_dir; ?>crests/<?php echo $away_crestsm; ?>" alt="<?php echo $away_team; ?>'s crest" /> <div class="form-group away_score score col-xs-6"> <input type="hidden" class="form-control" id="awayid_<?php echo $away_id; ?>" name="<?php echo 'away_ids[' . $match_id . ']'; ?>" value="<?php echo $away_id; ?>" /> <label class="sr-only" for="away_score">away score</label> <?php // if current time before match time, allow user pick match results if ($cur_time < $match_time) { if ((!empty($user_score_away) || ($user_score_away === 0)) && ($_session['user_rules'] == 'y')) { ?>       <!-- stackoverflow - match score updates --> <input type="number" min="0" class="form-control" id="away_score_<?php echo $match_id; ?>" name="<?php echo 'away_scores[' . $match_id . ']'; ?>" value="<?php echo $user_score_away; ?>" /> <?php } // if user has not yet agreed rules, not allow user pick match results elseif ((!empty($user_score_away) || ($user_score_away === 0)) && ($_session['user_rules'] == 'n')) { ?> <input type="number" min="0" disabled="disabled" class="form-control" id="away_score_<?php echo $match_id; ?>" name="<?php echo 'away_scores[' . $match_id . ']'; ?>" value="<?php echo $_post['away_scores'][$match_id]; ?>" /> <?php } else { ?>  <input type="number" min="0" class="form-control" id="away_score_<?php echo $match_id; ?>" name="<?php echo 'away_scores[' . $match_id . ']'; ?>" value="<?php echo $_post['away_scores'][$match_id]; ?>" /> <?php            } } // if current time after match time , match over, not allow user pick match results elseif ($cur_time >= date('y-m-d h:i', (strtotime('+95 minutes', strtotime($match_time))))) { ?> <input type="number" min="0" disabled="disabled" class="form-control" id="away_score_<?php echo $match_id; ?>" name="<?php echo 'away_scores[' . $match_id . ']'; ?>" value="<?php echo $user_score_away; ?>" /> <p class="alert-danger post_match_warning">results pending.</p> <?php } // if current time after match time match still playing, not allow user pick match results else { ?> <input type="number" min="0" disabled="disabled" class="form-control" id="away_score_<?php echo $match_id; ?>" name="<?php echo 'away_scores[' . $match_id . ']'; ?>" value="<?php echo $user_score_away; ?>" /> <p class="alert-danger post_match_warning">too late.</p> <?php  } ?> </div> </div> </div> </div> <?php } if (($cur_time < $match_time) && ($_session['user_rules'] == 'y')) { ?> <!-- stackoverflow - match score updates --> <div class="row"> <div class="form-group col-sm-4 col-sm-offset-4 col-xs-12"> <input type="submit" id="picks_submit<?php echo $match_id; ?>" class="btn btn-primary btn-lrg btn-block form-control submit" name="picks_submit<?php echo $match_id; ?>" value="update match" /> </div> </div> <!-- further code here --> </form><!-- end .teams_container/score input form -->  </div><!-- ends .past_match div --> <!-- remaining code below here --> 

i try explain in example , hope can make sense of it. sorry code long , not best formated , don't have time right make sense of it.

lets want update name in db table , don't want have multiple files.

<?php $connect = mysqli_connect('hostname', 'username', 'pass', 'dbname'); if(mysqli_connect_errno()){     echo 'connection error: ' . mysqli_connect_error();  }  function update($name, $id){   mysqli_query($connect,    "update `my_user_table` set `name`='$name' id=$id")   or die(mysqli_error($connection));   $success = '<p>success</p>';   return $success; }  if(isset($_post['name']) && isset($_post['id'])){   $myupdate = update($_post['name'], $_post['id']);   echo $myupdate;   exit; } ?>  <div id="formcont"> <form id="updateform" name="update" method="post">   <input type="text" name="name" id="name" />   <input type="hidden" name="id" value="1" />   <input type="submit" id="submit" name="submit" value="submit" /> </form> </div> <script> jquery(document).ready(function(){   $('#submit').click(function(){ //or can use on() instead of click()     var formdata = $('#updateform').serialize();     $.ajax({       type: "post",       cache: false, //or if want cache delete line       data: formdata,       success: function(data){         //do whatever want here         //for example remove form , print success text         $('#updateform').remove();         $('#formcont').append(data);       }     });   return false;   }); }); </script> 

this 1 example how can have php function(s) in same file , use ajax.


Comments

Popular posts from this blog

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -