php - ajax 和 php : how to select variables from database and insert in database using ajax

标签 php jquery mysql ajax mysqli

我以前真的从来没有这样做过,我很沮丧,因为我不确定它是如何组合在一起的。我有一个函数,我想调用我的 php(一个 php 文件从数据库中选择信息,第二个插入到数据库中)...我需要在我的网站设置方式中使用 ajax,但我不知道如何将数据从 php 文件传递​​到 php 文件。

在第一个 .js 文件中:

q1LoadVar();

这是我目前在第二个 .js 文件中的 ajax 函数(不工作):

//ajax code has been edited here since original post:

function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {

console.log(data); //nothing happens!
// alert(data); //nothing happens!

}, "json" );

}

这是我在 q1LoadVar1.php 中的代码,我想从中选择数据并能够填充我的 html 中的文本区域:

/*works when I type this file path directly into the url; 
but the file is not communicating back to the ajax function on the 
.js file that is calling it*/ 

<?php   
$config = parse_ini_file('../config.ini'); 
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);

if(mysqli_connect_errno()){  
echo mysqli_connect_error();  
}  

echo '<script type="text/javascript">alert("working from php!");</script>';

$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);

while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}

$json = json_encode($newRow);
echo $json; //works on php file directly!

/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/

mysqli_free_result($result);
mysqli_close($link);

?> 

有人可以帮助我了解如何让这一切协同工作吗?谢谢你,克里斯汀

最佳答案

您可以使用 php 中的 ajax 检索发布数据

$_POST['action']
//in your case will return: test

要返回数据给ajax你需要使用echo

如果成功:没有调用回调函数,尝试删除 datatype: 'json'

我还认为您需要回显 $newrow 而不是 $row

如果这仍然不起作用,您可以使用 error: 回调函数捕获错误以查看问题所在。

尝试从一个简单的请求开始,然后从那里着手。

$(document).ready(function() {

    $.ajax({
        type: "POST",
        url: "yourphp.php",
        data: {simplestring: "hi"},
        success: function(result){
            alert(result);
        }
    });
});

和你的php.php

<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;

关于php - ajax 和 php : how to select variables from database and insert in database using ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28971756/

相关文章:

php - 如何在 PHP 和 CSS 的 for 循环中正确定位 div

javascript - 绑定(bind)到单击事件来查找子元素输入值?

javascript - 事件处理程序返回 true J​​avascript jQuery

javascript - 将 json 对象合并到数据表中

javascript - 在javascript中读取sql查询输出

java - 如何使用 JDBI 的 Sql 对象 API 在运行时创建动态 Sql 查询?

mysql - 从具有值范围的列中获取数据

php - MySql 查询两个日期时间范围之间每个间隔的记录

php - 显示多行 MySQL

php - 即使未设置项目,isset() 函数也会返回 true