[英]PHP Not passing variables through to ajax
I am passing through The continent to the PHP
file from a js
file. 我正在从
js
文件通过大洲传递到PHP
文件。 Basically I need to insert the data to the database (put the continent in) and get the ID
of it, but no matter what I do, it returns either an empty string
or a 500 Internal Service Error
. 基本上,我需要将数据插入数据库(放入大洲)并获取它的
ID
,但是无论我做什么,它都会返回一个empty string
或500 Internal Service Error
。
Here is the PHP Code
: 这是
PHP Code
:
$continent = $_POST['continent'];
$sql = "INSERT INTO location_continent (`name`) VALUES ('". $continent ."')";
if(!$result = mysqli_query($con, $sql)){
die('There was an error running the query [' . $db->error . ']');
}
$sql = "SELECT id FROM location_continent WHERE `name` = '". $continent ."'";
$result2 = $con->query($sql);
if(!$result2){
die('There was an error running the query [' . $con->error . ']');
}
return $result2->num_rows;
Here is the JS Code
: 这是
JS Code
:
$.ajax({
url: 'process.php?section=continent',
type: 'POST',
data: 'continent='+key,
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
The Key
that is passed through would be something like Africa
. 通过的
Key
将类似于Africa
。
I have tried the following in the php file
: 我在
php file
尝试了以下内容:
return mysqli_insert_id($conn);
return $result;
$result = mysqli_query($con, $sql);
I have struggled for around 2 hours now. 我已经奋斗了大约2个小时。 I cannot seem to find the error.
我似乎找不到错误。
Note Please note that the information is being inserted to the database just fine, just that I cannot get the ID. 注意请注意,信息正好插入到数据库中,只是我无法获取ID。
In ajax you need to print/echo output for return data rather return statement so try to replace 在ajax中,您需要打印/回显输出以获取返回数据而不是return语句,因此请尝试替换
return $result2->num_rows;
to 至
echo $result2->num_rows;
also you can send your query string like:- 您也可以发送查询字符串,例如:
$.ajax({
url: 'process.php',
type: 'POST',
data: {'section':'continent','continent':key},
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
Then check your post data by echo if correct something wrong with query executing can't find $con
and $db
defined on posted code 然后通过回声检查您的发布数据,以解决查询执行中的错误,找不到发布代码中定义的
$con
和$db
您正在返回,但您不在函数中,因此请尝试使用echo mysqli_insert_id($conn);
( echo mysqli_insert_id($conn);
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.