Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我的PHP代码会干扰我的AJAX代码?_Php_Ajax - Fatal编程技术网

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

为什么我的PHP代码会干扰我的AJAX代码?,php,ajax,Php,Ajax,当我提交一个名为functions\u question2的表单时,我有以下PHP代码来更新mySql数据库: $id = $_SESSION['id']; if(isset($_POST['functions_question2'])){ if($id){ $res3 = $db->query("SELECT * FROM answers WHERE user_id=$id"); $data3 = $res3->fetch_array();

当我提交一个名为
functions\u question2
的表单时,我有以下PHP代码来更新mySql数据库:

$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");
}
我还有以下AJAX代码,用于在提交表单时运行JQuery函数:

    <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>

$(文档).ready(函数(){
$('functions_question2')。关于('submit',function(e){
e、 预防默认值();
$.ajax({
url:$(this.attr('action')| | window.location.pathname,
类型:“POST”,
数据:$(this).serialize(),
成功:功能(数据){
$.ajax(“ajax.php?module=user\u functionsCore”).success(函数(结果){
var color2=结果;
$(“#div2”).css(“背景色”,color2);
if($('input[name=functions\u question2]:checked').val()==2){
美元(“.correctanswermark”).fadeIn('slow');
}否则{
美元(“.correctanswermark”).fadeIn('slow');
}
});
},
});
});
});
它们都在脚本的开头,AJAX位于PHP代码的下面。每一个都可以在没有另一个的情况下工作,但是当它们都在文档中时,只有PHP代码运行。当代码中同时出现这两种情况,并且我提交表单时,页面似乎会刷新,这可能会显示AJAX代码没有运行

如果有人能帮我弄清楚为什么PHP正在取代AJAX代码,我将不胜感激。谢谢

<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>


开发人员控制台中有错误吗?没有,我按了ctrl+shift+J,它没有返回任何错误。您可以尝试记录
$\u SESSION
$\u POST
并确保正确设置值吗?此外,请张贴的html,即表单的其余部分。接下来,将
javascript
放在
标记的正上方。使用
console.log
记录重要事件,直到确保一切按预期进行。此外,使用developer tools或Firebug中的Network选项卡检查您从ajax调用中得到的响应和http状态代码。“用户提交的答案”在PHP的中间没有编译。我张贴了整个代码“安东尼奥亚历山大”。在开发控制台有任何错误吗?不,我做了Ctrl + Shift + J,它没有返回任何错误。你可以尝试记录<代码> $ySudio<<代码>和<代码> $POST < /代码>,并确保这些值被正确设置吗?此外,请张贴的html,即表单的其余部分。接下来,将
javascript
放在
标记的正上方。使用
console.log
记录重要事件,直到确保一切按预期进行。此外,使用developer tools或Firebug中的Network选项卡检查您从ajax调用中得到的响应和http状态代码。“用户提交的答案”在PHP的中间没有编译。我张贴了整个代码“安东尼奥亚历山大”。