简体   繁体   中英

JQuery Ajax Updating MySQL Database, But Not Running Success Function

I am currently using the JQuery ajax function to call an exterior PHP file, in which I select and add data in a database. Once this is done, I run a success function in JavaScript. What's weird is that the database is updating successfully when ajax is called, however the success function is not running. Here is my code:

<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
</head>
<body>
<div onclick="addtask();" style="width:400px; height:200px; background:#000000;"></div>
<script>
function addtask() {
var tid = (Math.floor(Math.random() * 3)) + 1;
var tsk = (Math.floor(Math.random() * 10)) + 1;

if(tsk !== 1) {
    $.ajax({
    type: "POST",
    url: "taskcheck.php",
    dataType: "json",
    data: {taskid:tid},
    success: function(task) {alert(task.name);}
    });
}
}

</script>
</body>
</html>

And the PHP file:

session_start(); 

$connect = mysql_connect('x', 'x', 'x') or die('Not Connecting'); 
mysql_select_db('x') or die ('No Database Selected'); 

$task = $_REQUEST['taskid']; 
$uid = $_SESSION['user_id']; 

$q = "SELECT task_id, taskname FROM tasks WHERE task_id=" .$task. " LIMIT 1"; 
$gettask = mysql_fetch_assoc(mysql_query($q)); 

$q = "INSERT INTO user_tasks (ut_id, user_id, task_id, taskstatus, taskactive) VALUES (null, " .$uid. ", '{$gettask['task_id']}', 0, 1)"; 
$puttask = mysql_fetch_assoc(mysql_query($q)); 

$json = array( 
    "name" => $gettask['taskname'] 
); 

$output = json_encode($json); 
echo $output; 

Let me know if you have any questions or comments, thanks.

在此处输入图像描述

Ibelieve it runs but alert wont show because of error -

success: function(task) {alert(task.name);} 

You have to decode JSON first with jQuery.parseJSON() , task is just a string it shoudld look somthing like this

function(m)
        {
            var task = jQuery.parseJSON( m );
            alert(task['name']);
        }

Edit: Ok... Try to use developer tools in your browser and place breakpoint on your success function, if it doesnt even lunch try to add error callback for your ajax call

error: function(xhr, exc)
{
   alert(xhr.status);
   alert(exc);
}

Edit2: and there is your problem - your ajax is not only returning json data, but php warning too, and now I see where is your problem - you are fetching data after insert, delete

$puttask = mysql_fetch_assoc(mysql_query($q));

Now I feel bad for not noticing it sooner...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM