下記のようにajaxでデータベースにアクセスしユーザ入力情報がDBに既に登録されていないかを
チェックしたいと考えております。
confirm.phpで取得した値に基づき、
if (result=="usedname"){
//使用済みのユーザ名の場合の処理
}else if{
//未使用のユーザー名の処理
}
としたいのですが、"<script> const result = usedname <script>"
をheadにappendしてもif判定の時点でまだ読み込まれていないためresultがundefined
扱いになってしまいます。
- 受け取った値をindex.phpの非同期通信成功時に変数として処理したいのですがどのように受け渡せば良いのでしょうか?
- それとは別にajaxでデータベースに既登録情報のチェックという意味でより実務的にこうすべき、またはこれが一般的という方法があれば合わせてアドバイスをいただければ嬉しいです。
*コードを修正しました
php
1//index.php 2$(function(){ 3errCode[]="" 4 $(document).on('click','.button',function(){ 5 $.ajax({ 6 type:'POST', 7 url:'confirm.php', 8 datatype:'json', 9 data:{ 10 transfer_name:username 11 } 12 }) 13 .then( 14 function(data){//success 15 console.log(result)// {"status":false} 16 console.log(result.status)// undefined 17 if (result) { 18 errCode.push("usedname") 19 $('#er').remove(); 20 $('<p id="er" class="errmessage">すでに使用されているユーザ名です</p>').appendTo('.errmessagebox').hide().fadeIn(1000); 21 }else{ 22 $('#er').remove(); 23 } 24 }, 25 function(){//fail 26 console.log('...failed'); 27 } 28 ) 29 }) 30})
php
1//confirm.php 2 3<?php if ($_POST['transfer_name']): ?> 4 <?php include('./z_common_pdo.php');?> 5 <?php 6 try{ 7 $pdo->beginTransaction(); 8 try{ 9 $stmt = $pdo->prepare('SELECT * FROM user_table where username=:uname'); 10 $stmt->bindParam(':uname',$_POST['transfer_name'],PDO::PARAM_STR); 11 $stmt->execute(); 12 13 $result=$stmt->fetch(PDO::FETCH_ASSOC); 14 $pdo->commit(); 15 }catch(PDOException $e){ 16 $pdo->rollback(); 17 throw $e; 18 } 19 }catch(PDOException $e){ 20 exit('データベース接続失敗。'.$e->getMessage()); 21 } 22 ?> 23 <?php 24 echo json_encode(["status"=> $result]); 25 ?> 26<?php else:?> 27 <p>無効な処理です、リダイレクトします</p> 28<?php endif;?>
回答3件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/24 00:07
2018/10/24 00:19
2018/10/24 03:11
2018/10/24 03:26
2018/10/24 03:49
2018/10/24 03:54
2018/10/24 04:01
2018/10/24 04:03
2018/10/24 04:35
2018/10/24 04:38
2018/10/24 04:41
2018/10/24 04:43
2018/10/24 04:47
2018/10/24 04:50
2018/10/24 04:52
2018/10/26 03:15
2018/10/26 03:28