My ajax code from javascript
function makeRequest(button) {
alert(button.value);
var no =button.value;
$.ajax({
url: "findques.php",
type: 'POST',
dataType:"json",
data: {id:no},
success: function(response) {
$.each(response, function(idx, res){
alert(res.question);
});
},
error:function(err){
console.log(err);
}
});
}
My php code to retrive data is as follows
<?php
$connect =mysql_connect('localhost', 'root', 'password');
mysql_select_db('test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
if(isset($_POST['id']))
{
$var = mysql_real_escape_string(htmlentities($_POST['id']));
error_log($var);
}
$data = "SELECT * FROM `questions` WHERE no=$var";
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
else{
echo "error";
}
$connect->close();
?>
Im trying to retrive data from Mysql database from ajax through php but it shows me "error.jquery.min.js:6 GET 500 (Internal Server Error)"
Is that a problem with my ajax part or PHP part?? Im using Ubuntu 14.04 with apache 2 server.Some suggest there is a problem with server permissions??
You're using type: 'GET', and in PHP you're using $_POST['id'].
Change type to type: 'POST',
Your problem is invalid php code.
It appears you are using some strange mix of different examples on the server side:
$connect =mysql_connect('localhost', 'root', 'password');
This line returns a handle (a numeric value), and not an object which is what you try to use later on:
if($connect->connect_error)
This leads to an internal error.
To debug things like this you should start monitoring the error log file of your http server. That is where such errors are logged in detail. Without looking into these log files you are searching in the dark. That does not make sense. Look where there is light (and logged errors)!
I used mysqli instead of mysql_connect() and error is gone since mysql_connect() is deprecated on suggestions of patrick
Try changing this...
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
To this...
$result = mysql_query($data);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_assoc($result);
$details =array(
"id"=>$row['no'],
"question"=>$row['Ques'],
"op1"=>$row['op1'],
"op2"=>$row['op2'],
"op3"=>$row['op3'],
"op4"=>$row['op4']);
echo json_encode($details);
}
Not 100% sure that's the problem, but that's how I structure my basic DB functions, and it works fine.
I would also note that if this is going to to be a public page where users can enter data, I recommend using PHP PDO to handle your database interactions.
Related
I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}
my problem is the following...
I made some php code that reads records from a mysql database:
$host = $_SESSION['host'];
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$db = $_SESSION['db'];
$con = mysqli_connect($host,$username,$password,$db);
$sql = "SELECT * FROM `table`";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
...
}
}
my html:
<button onclick="list">submit</button>
<div id="output"></div>
<script>
var thisHost = "host.php";
function list() {
$.ajax({
type: 'POST',
url: thisHost,
data: "list=true",
success: function(data)
{
$("#output").html(data);
},
error: function (responseData, textStatus, errorThrown)
{
console.warn(responseData, textStatus, errorThrown);
}
});
}
</script>
as far as that everything is working fine. However now i want to call the php code from another host. Therefor the html file is on the other host (localhost:81) and the php file stays on the old host (localhost:80).
now I noticed that i need a something to cross the domain because ajax doesn't seem to work with other hosts. So all i did was adding these lines to the php code right at the beginning:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
and change the value of the thisHost var in javascript to
"http://localhost:80/host.php"
after that the ajax part works again and the php response. However every time i want to make a query by doing something like this:
$sql = "SELECT * FROM `table`";
i will get this error:
Fatal error: Uncaught Error: Call to a member function query() on null
in C:\path\to\host.php:71 Stack trace: #0 {main} thrown in
C:\path\to\host.php on line 71
i'm pretty sure that the query is correct. So what do i need to change?
Calling a method on an invalid handle will produce errors like this. Always check that your connection request succeeded and handle any errors that could have occurred.
Turning on mysqli exceptions makes these things a lot harder to ignore.
i'm trying to understand this error but i dont how to solve it
this is my JS code:
$.ajax({
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
type: "POST",
data: ({Pname: Pname, Uname: Uname, email: email, Ename: Ename, Sigla: Sigla}),
complete:function(data)
{
resposta = data;
console.log(resposta);
}
});
this is my php code:
$serverName = $server;
$uid = $uid;
$pwd = $pass;
$connectionInfo = array( "UID" => $uid, "PWD" => $pwd,"Database"=>"Portal");
//$connectionInfo = array("Database"=>"Portal");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$Pname = $_POST["Pname"];
$Uname = $_POST["Uname"];
$email = $_POST["email"];
$Ename = $_POST["Ename"];
$Sigla = $_POST["Sigla"];
if( $conn )
{
$sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ($Ename, $Sigla)";
if (mysqli_query($conn, $sqlCliente)) {
echo "New record created successfully";
} else {
echo "Error: " . $sqlCliente . "<br>" . mysqli_error($conn);
}
}
when i do console.log of data, give me this:
what is wrong with my code?
Try to change into $sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ('$Ename', '$Sigla')";
I think problem with your sql insert statement.
$sqlCliente = "INSERT INTO Portal.dbo.Empresa(Ename,Sigla) VALUES ($Ename, $Sigla)";
OR
$sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ($Ename, $Sigla,..... Add all parameters to here)";
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
This line is incorrect.
PHP files need a server to get executed. By the looks of your path, it looks like you have hosted in IIS. IIS doesn't suppport PHP by default - so assuming you have installed PHP and configured properly, read below.
You don't post to the physical path of the PHP file, rather URL of the PHP.
Therefore, it should look something similar to:
url: localhost/VisionwareHelp/php/CriaUserEempresa.php',
Until you fix the URL to the correct one, none of your posting code will work correctly.
If you have not installed PHP on IIS, then you need to download and install a PHP-enabled server like 'WampServer' and host your PHP in that.
Also, read below articles - it will help to improve your knowledge.
Installing and Testing Wampserver
Beginner’s Guide to Ajax Development with PHP
In Ajax, The correct syntax of sending multiple data is: http://api.jquery.com/jQuery.ajax/
So, Replace
data: ({Pname: Pname, Uname: Uname, email: email, Ename: Ename, Sigla: Sigla}),
with
data: {'Pname':Pname, 'Uname':'Uname', 'email':email, 'Ename':Ename, 'Sigla':Sigla },
And this line url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php', is also incorrect.
replace
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
with
url: 'Php/CriaUserEempresa.php',
Hope it will help you..
I am trying to add some data to a relational database, and would like the session_user_id to be the foreign key for that database. When a user clicks a button, I want to make a database entry with the session_user_id and some other information I have POSTed to the page. My ajax posts to the php webpage page which it is run on (meaning all my scripts are on the same page)
I am currently getting a Uncaught ReferenceError: $sess_user_id1 is not defined. The jquery is firing. While I would love to get the undefined variable fixed, overall this does not seem like a very direct way to to this, and has added a bunch of confusing variables, when all the variables I need were already in my PHP statement. Is there any way to trigger the PHP entry without going through ajax and having to define the variables again?
Here is my php, which is at the header which is on the same page as my JS and HTML:
<?php
$markerid = $_POST["id"];
$name = $_POST["name"];
$type = $_POST["type"];
$point = $_POST["point"];
$lat2 = $_POST["lat"];
$lng2 = $_POST["lng"];
$locationdescription = $_POST["locationdescription"];
$locationsdirections = $_POST["locationdirections"];
session_start();
if (!isset($_SESSION['sess_user_id']) || empty($_SESSION['sess_user_id'])) {
// redirect to your login page
exit();
}
$sess_user_id1 = $_SESSION['sess_user_id'];
if ((isset($_POST['usid'])) && (isset($_POST['usid']))) {
$user_id_follow = strip_tags($_POST['usid']);
echo $user_id_follow;
$query = "INSERT INTO markerfollowing ( userID, markerID, type )
VALUES ('$user_id_follow', '$markerid', '$type');";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_close();
}
?>
Here is the HTML button:
<div class="btn pull-right">
<button class="btn btn-large btn-followmarker" type="submit"id="followmarker">Add me to the list</button>
</div>
Here is the jquery/ajax post:
<script/javascript>
$(document).ready(function () {
$("#followmarker").click(function(){
$.ajax({
type: "POST",
url: "", //
data: { usid: <?php echo '$sess_user_id1'; ?>},
success: function(msg){
alert("success");
$("#thanks").html(msg);
},
error: function(){
alert("failure");
}
});
});
});
</script
A sincere thanks for any and all help. I haven't worked with relational databases before.
<?php echo '$sess_user_id1'; ?>
is wrong. If you wont to get
data: { usid: 123} at $sess_user_id1 is 123, you should write
data: { usid: <?php echo "$sess_user_id1"; ?>}
See your html source code in your brawser. I think there is data: { usid: $sess_user_id1}, and javascript is not understand what is the $sess_user_id1
This is the only one problem that I can see now, but I don't understand your current task whole to say more.
I want to make a javascript function which checks the database whether the id requested by the user is available or not. My code is:
HTML:
<button type="button" onclick="chkId()">Check Availability</button><span id="chkresult"></span>
Javascript code:
function chkId()
{
$("#chkresult").html("Please wait...");
$.get("check_id.php", function(data) { $("#chkresult").html(data); });
}
The check_id.php file:
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
echo "Available!";
}
else if ($total > 0)
{
echo "Not Available!";
}
?>
But when the button is clicked, nothing happens. I just get a 'Please wait...' message, but as expected by the code, after 'Please wait...' it should change either to Available or to Not Available. But I only get the 'Please Wait...' message, and the result Available or Not Available is not printed on the screen. Please help me what changes do I need to make in my code.
I do not see the $id variable in your PHP script that is used by your $id_query.
Try adding that above $id_query
A few things I notice:
Your javascript is not passing the id parameter to your php backend. See the documentation for the proper syntax to pass that id param.
Your PHP is calling the mysql_query method and one of the parameters that it is passing in is the $id - but $id has not been declared. Check your PHP logs and you'll see where it is choking.
Because the PHP code is likely failing due to the unresolved variable, it is returning an error code. When JQuery receives the error code, it goes to call your ajax failure handler, but you have not declared one! Try adding a .fail(function(){}); to your get call as the docs describe - and you'll likely see the php error message show up.
EDIT: Obligatory php sql injection attack warning. Make sure to escape client input!!!
$.ajax({
type: "POST",
url: "check_id.php",
data: {
id:id; //the id requested by the user.You should set this
},
dataType: "json",
success: function(data){
$('#chkresult').html(data);
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
In your php
<?php
require 'connect.php';
$id_query = mysql_query("SELECT COUNT(*) AS TOTAL FROM `Table4` WHERE `Unique ID` = '$id'");
list ($total) = mysql_fetch_row($id_query);
if ($total == 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Available');
}
else if ($total > 0)
{
header('Content-type: application/json');
echo CJavaScript::jsonEncode('Not available');
}
?>