dthjnc306679 2017-06-28 02:45
浏览 32

为什么我的PHP代码干扰了我的AJAX代码?

I have the following PHP code to update mySql database when I submit a form with an input named functions_question2:

$id = $_SESSION['id'];
if(isset($_POST['functions_question2'])){
    if($id){
        $res3 = $db->query("SELECT * FROM answers WHERE user_id=$id");
        $data3 = $res3->fetch_array();
        if(isset($_SESSION['functions_question2']) && $_POST['functions_question2']==$_SESSION['functions_question2']){  
$db->query("UPDATE answers SET FunctionsScore = FunctionsScore+1 WHERE user_id=$id");
}

I also have the following AJAX code to run a JQuery function when the form is submitted:

    <script type='text/javascript'>
$(document).ready(function () {
    $('functions_question2').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {
            $.ajax("ajax.php?module=user_FunctionsScore").success(function(result){
                var color2 = result;
                $("#div2").css("background-color", color2);
                if ($('input[name=functions_question2]:checked').val()  == 2)  {
                    $(".correctanswermark").fadeIn('slow');
                } else {
                    $(".correctanswermark").fadeIn('slow');
                }
                  });
            },
        });
    });
});
</script>

They're both in the head of the script, with the AJAX below the PHP code. Each also works without the other, but when they're both in the document, only PHP code runs. The page appears to refresh when both are present in the code and I submit the form, which may give the appearance that the AJAX code is not running.

If someone would help me figure out why the PHP is superceding the AJAX code, I would greatly appreciate it. Thanks!

<html>
<head>

<?php
include "inc/db.php";
session_start();
error_reporting(E_ALL);
//Identifying it the user is logged in or if it's a guest
//then if he is logged in, we will get it's ID
if(isset($_SESSION['id'])){
    //the user is registered
    $id = $_SESSION['id'];
    echo 'Welcome, '.$_SESSION['name'].'!<br><br>';
}else{
    //the user is a guest
    $id = 0;
    echo 'Welcome, guest! Click <a href="framework_account.php">here to login or register</a>!<br><br>';
    if(isset($_COOKIE['guestdata'])) $cookiedata = json_decode($_COOKIE['guestdata']);
    else{
        //else, we just create a new array with the values
        $cookiedata = array();
        $cookiedata['score'] = $cookiedata['FunctionsConsistency'] = $cookiedata['FunctionsScore'] = $cookiedata['FunctionsPercent'] = $cookiedata['FunctionsLevel'] = 0;
    }
}

//<!--//////////////////////////////////////////////////// UPDATING FUNCTIONSSCORE BY SUBMITTING functionsquestionform2   -->

//$id = $_SESSION['id'];
var_dump("SELECT * FROM answers WHERE user_id=$id");

//Now, the 2nd part... We will increase/decrease the score in the same file, so the user will submit the answer to the same file, and we will do this with php:
if(isset($_POST['functions_question2'])){
    //|This if checks if there was a form submited - it will only run if the user submitted an answer
    //now:
    if($id){
        //The user is logged in, so we make the queries on the database
        $res3 = $db->query("SELECT * FROM answers WHERE user_id=$id");
        $data3 = $res3->fetch_array();
        $LevelColumnAdder=$_POST['LevelColumnAdder']; // Takes the value of the hidden input named "Level Column Adder" ...
        if(isset($_SESSION['functions_question2']) && $_POST['functions_question2']==$_SESSION['functions_question2']){  
$db->query("ALTER TABLE answers ADD $LevelColumnAdder VARCHAR( 255 ) NOT NULL");  // ...and creates a column named after "Level Column Adder"'s value
            if($data3['FunctionsScore']<2 )$db->query("UPDATE answers SET FunctionsScore = FunctionsScore+1 WHERE user_id=$id");
            if($data3['FunctionsScore']=2)$db->query("UPDATE answers SET FunctionsScore = FunctionsScore+0 WHERE user_id=$id");
        if($data3['FunctionsPercent']<49)$db->query("UPDATE answers SET FunctionsPercent = FunctionsPercent+2 WHERE user_id=$id");
        if($data3['FunctionsPercent']>50 && $data3['FunctionsPercent']<100)$db->query("UPDATE answers SET FunctionsPercent = 50 WHERE user_id=$id");
    }else{
  if($data3['FunctionsScore']>-2 )$db->query("UPDATE answers SET FunctionsScore = FunctionsScore-1 WHERE user_id=$id");
    if($data3['FunctionsPercent']<49)$db->query("UPDATE answers SET FunctionsPercent = FunctionsPercent+2 WHERE user_id=$id");
        if($data3['FunctionsPercent']>50 && $data3['FunctionsPercent']<100)$db->query("UPDATE answers SET FunctionsPercent = 50 WHERE user_id=$id");
$hiddeninput=$_POST['hiddeninput'];
$db->query("INSERT INTO answers (user_id, ProblemNameTest) VALUES ($id,'$hiddeninput')");
}
    }else{
        //The user is a guest
        $data3 = (array)$cookiedata;
        $cookiedata = $data3;
        $cookie = json_encode($data3);
        setcookie('guestdata', $cookie, time()+25920000);

    }
}
if($id){
    //if the user is logged in
    $data = $db->query("SELECT * FROM answers WHERE user_id=$id")->fetch_array();
}else{
    $data = (array)$cookiedata;
    //the user is a guest;
}
$Percentpercent = $data['FunctionsPercent'];
$FunctionsScore= $data['FunctionsScore'];
$FunctionsLevelTEST = $data['FunctionsLevel'];
$FunctionsConsistencyTest = $data['FunctionsConsistency'];
?>







<?php



   $data5 = $db->query("SELECT GROUP_CONCAT(DISTINCT ProblemNameTest ORDER BY rand()) as ProblemNameTest FROM (SELECT ProblemNameTest FROM answers WHERE user_id=$id AND ProblemNameTest LIKE 's%') AS ProblemNameTest")->fetch_assoc();
$selector= $data5['ProblemNameTest'];
$selectorfirst=str_word_count($selector, 1);
?> 



<?php echo "|||THIS IS WHERE SELECTOR SHOULD SHOW UP:"; echo $selectorfirst[0]; ?>





<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type='text/javascript'>
$(document).ready(function () {
    $('functions_questions2').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "POST",
            data: $(this).serialize(),
            success: function (data) {
            //after the UPDATE request was made, we do the GET request to get the current user color, so:
            $.ajax("ajax.php?module=user_FunctionsScore").success(function(result){
                var color2 = result;
                //getting the data sent by ajax
                //and now updating the color with jquery
                $("#div2").css("background-color", color2);
                //once with this we will show the answer to the user
                if ($('input[name=functions_question2]:checked').val()  == 2)  {
                    $(".correctanswermark").fadeIn('slow');
                    $(".incorrectanswermark").fadeIn('slow');
                } else {
                    $(".correctanswermark").fadeIn('slow');
                    $(".incorrectanswermark").fadeIn('slow');
                }
});
            },
        });
    });
});
</script>




<script type='text/javascript'> /////THIS IS THE CODE THAT CAUSES CLICKING DIV WITH CLASS ".SUBMITTER" TO SUBMIT ITS PARENT FORM.
$(document).ready(function () {
$("div.submitter").click(function(){
    $(this).parent().submit();
    //$(this).find("button").click();
});
});
</script>


<!--////////////////////////////////////////////////////// THIS APPEARS TO BE USELESS FOR AUTOMATICALLY UPDATING COLOR BUT IT DOES AUTOMATICALLY SHOW CHECKMARKS-->



<style type="text/css">
.img-box
       {
padding-top: 25px;
    border-bottom: 5px solid #333;
}
</style>
<style>
label {
    display: block;
}
</style>

</head>

<!--////////////////////////////////////////////////////// SCROLLBAR BASICS -->

<div id="alternatewrapper" class="wrapper">
<form>
      <input type="hidden" name="SubmitToAddTestActiveClass" value="SubmitToAddTestActiveClassValue">  
    <div  class="submitter" class="randomizereasyorhard" id="carouselbutton1" style="width:140px;height:140px;background-color:transparent;display:inline-block;text-align:center;line-height: 140px;border: 2px solid black;border-radius: 10px;"><font face="Courier New"><font face="Courier New">Question Set 1</font></font></div>
    <div class="carouselbutton" id="carouselbutton2" style="width:140px;height:140px;background-color:transparent;display:inline-block;text-align:center;line-height: 140px;border: 2px solid black;border-radius: 10px;"><font face="Courier New">Question Set 2</font></div>
</form>
</div>
</div>

<!--//////////////////////////////////////////////////////WITHOUT THIS, DIV2 COLOR DISAPPEARS ON REFRESH -->

<?php


 $color=getColor($data['score']);
$color2=getColor2($data['FunctionsScore']);

?>




<!--////////////////////////////////////////////////////// THE BELOW CODE SELECTS A VALUE FROM THE MYSQL ($db defined in one of the external files) -->
CHECKS VALUES 
<?php echo "||| Functions Percent"; echo $Percentpercent; ?>
<?php echo "||| Functions Score"; echo $FunctionsScore; ?>
<?php echo "||| Functions Level"; echo $FunctionsLevelTEST; ?>
<?php echo "||| Functions Consistency"; echo $FunctionsConsistencyTest; ?>
<?php echo $scoreTest; ?>
FunctionsScore: <?php echo $data['FunctionsScore']; ?>

<div id="div2" style="width:80px;height:80px;background-color:<?php echo $color2; ?>;">Should immediately update when functionsquestionform2 submitted</div>
<br>
<div id="functionpanel" class="colortest" style="background-color:orange; color:black; border-style:solid; border-width:1px; padding:20px;">
<p style="margin:0;"><b></b></p>
<form class ="functionsquestionform2" id = "logoutForm' class = "classtest" action="frameworkplayground.php" method="POST">
    <input type="hidden" name="hiddeninput" value="FirstProblem">  
<input type="hidden" name="LevelColumnAdder" value="Simplifying_Fractions">  
     This is functionsquestionform2  Select the correct answer.


    <div class="blahblah" id="questions">
        <label>
            <input type="radio" id="blah"  name="functions_question2" value="2">  This is the correct answer. <span class="correctanswermark" style="color:green; display: none; font-size: 150%;">&#10003</span><span id="correctanswermarkwhengotwrong" style="color:black; display: none; font-size: 120%;">&#8592;&nbspActually, this is the correct answer.</span></input>
        </label>     
        <label>
            <input type="radio" id="blah" class ="functionsquestionform2" name="functions_question2" value="1"> Wrong. <span class="incorrectanswermark" style="color:red; display: none; font-size: 120%;">&#10007</span></input>
        </label>        
      <label>
             <input type="radio" id="blah" class ="functionsquestionform2" name="functions_question2" value="3"> Wrong. <span class="incorrectanswermark" style="color:red; display: none; font-size: 120%;">&#10007</span></input>
        </label>     
    </div>
        <br/>
        <br/>

        <br/><br/>

  <div class="submitter">Please Click Me</div>
<input type="submit" id="samplesubmitbutton" value="Click Me" style="width:300px;">  ///Don't Need this

</form>



THIS IS THE SECOND OF THE CLASS: Harbors SecondProblem
<form  class = "classtest" action="frameworkplayground.php" method="POST">
    <input type="hidden" name="hiddeninput" value="SecondProblem">  
     This is functionsquestionform2  Select the correct answer.


    <div class="blahblah" id="questions">
        <label>
            <input type="radio" id="blah" name="functions_question2" value="2">  This is the correct answer. <span class="correctanswermark" style="color:green; display: none; font-size: 150%;">&#10003</span><span id="correctanswermarkwhengotwrong" style="color:black; display: none; font-size: 120%;">&#8592;&nbspActually, this is the correct answer.</span></input>
        </label>     
        <label>
            <input type="radio" id="blah" name="functions_question2" value="1"> Wrong. <span class="incorrectanswermark" style="color:red; display: none; font-size: 120%;">&#10007</span></input>
        </label>        
      <label>
             <input type="radio" id="blah" name="functions_question2" value="3"> Wrong. <span class="incorrectanswermark" style="color:red; display: none; font-size: 120%;">&#10007</span></input>
        </label>     
    </div>
        <br/>
        <br/>

        <br/><br/>
<input type="submit" id="samplesubmitbutton" value="Click Me" style="width:300px;">
</form>






<?php
    $_SESSION['functions_question2']=2;
?>
</div>

<script type='text/javascript'>
$(function(){ 
var selectorvar = "<?php echo $selectorfirst[0]; ?>"
var selectorvar1=selectorvar;
 $('input[value="'+selectorvar1+'"]').closest("form").css("display", "none"); ///Use "display","block" to show
});
</script>


<!--////////////////////////////////////////////////////// PERCENTAGE OF SCROLLBARS THAT ARE COLORED -->
<script type='text/javascript'>
$(function(){
var carouselbutton1percentage = "<?php echo $Percentpercent; ?>"
var percentage=carouselbutton1percentage,
    col1="#72CF2F",
    col2="white";
var t=document.getElementById('carouselbutton1');
t.style.background = "-webkit-gradient(linear, left bottom,left top, color-stop("+percentage+"%,"+col1+"), color-stop("+percentage+"%,"+col2+"))";
t.style.background = "-moz-linear-gradient(bottom center,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
t.style.background = "-o-linear-gradient(bottom,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
t.style.background = "linear-gradient(to top,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
});
$(function(){
var carouselbutton2percentage=50
var percentage=carouselbutton2percentage,
    col1="#F2F5A9",
    col2="white";
var t=document.getElementById('carouselbutton2');
t.style.background = "-webkit-gradient(linear, left bottom,left top, color-stop("+percentage+"%,"+col1+"), color-stop("+percentage+"%,"+col2+"))";
t.style.background = "-moz-linear-gradient(bottom center,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
t.style.background = "-o-linear-gradient(bottom,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
t.style.background = "linear-gradient(to top,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
});
</script>




<!--////////////////////////////////////////////////////// USES PHP CONDITIONS TO CHANGE VISIBILITY OF DIV IN ANSWERS -->
<script type='text/javascript'>
$(function(){
leveldeterminant="<?php echo $FunctionsLevelTEST; ?>"
consistencydeterminant="<?php echo $FunctionsConsistencyTest; ?>"
scoredeterminant="<?php echo $scoreTest; ?>"
if (leveldeterminant == 0 && consistencydeterminant <3) {
    $("#oneasystayeasy").fadeIn('fast');
} else if (leveldeterminant == 0 && consistencydeterminant == 3 && scoredeterminant == 2) {
      $("#oneasygohard").fadeIn('fast');
} else if (leveldeterminant == 1 && scoredeterminant <0) {
      $("#onhardgoeasy").fadeIn('fast');
} else if (leveldeterminant == 1 && scoredeterminant >-1) {
    $("#onhardstayhard").fadeIn('fast');
}
});
function get_user_scores(){
    //The function for retrieving the user's data from the ajax module
    $.get("ajax.php?module=user_scores").done(function(data){
        //after making the request and getting the JSON data, we parase it, and we save it into our variables
        var data =  JSON.parse(data);
        leveldeterminant = data.FunctionsLevel;
        consistencydeterminant = data.FunctionsConsistency;
        scoredeterminant = data.score;
        if(data.FunctionsLevel==0 && data.FunctionsConsistency < 3){
            $("#easytohard").show();
        }
    });
}
</script>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 WPF 大屏看板表格背景图片设置
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
    • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
    • ¥16 mybatis的代理对象无法通过@Autowired装填
    • ¥15 可见光定位matlab仿真
    • ¥15 arduino 四自由度机械臂
    • ¥15 wordpress 产品图片 GIF 没法显示