Fetch data from database and send it to javascript function - javascript

I am selecting input values from the database and I want to send it to the javascript function addVal() so that I can retrieve this value. I do not want to use echo. It is not working right now and I don't know how I can make it work.
<h1>trial,</h1>
<div id ="val"> </div>
<?php
$name = $_POST['postname'];
$host = 'localhost';
$user = 'root';
$pass = 'root';
$db_name="big";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "connected";
$sql = "SELECT input FROM trial_db";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$value = $row['input'];
addVal ($value);
}
}
?>
<script>
function addVal (value){
document.getElementById("val").innerHTML+= value ;
}
</script>

Calling js function from php will not work remove that code from php.
And change in js.
<script>
function addVal (){
var value = "<?php echo $value; ?>";
document.getElementById("val").innerHTML+= value ;
}
</script>
Will only work if js and php codes are in same php file.

Related

Success function in ajax not returning anything in console

Here is my code, and while running it's not giving anything in the console.
This is how I am trying to check the data. If the data correctly I want the mentioned console in success code. But if it is not then I want else code to run. But the if-else conditions are not working properly. I am including PHP code and ajax code which I have tried. Am I doing it right?
<?php
$host = "dpydaldermt01.******.com";
$username = "test";
$password = "Test";
$database_name = "test";
$conn = mysqli_connect($host, $username, $password, $database_name) or die("Connection failed: " . mysqli_error());
$sql = "select ID, user_email from ci_iwp_wp_users limit 10";
$result = mysqli_query($conn, $sql);
$users = array();
?>
<script>
(function($) {
<?php
while($row = mysqli_fetch_assoc($result)) {
$email = $row['user_email'];
?>
var mail = "<?php echo $email ?>";
$.ajax({
type:'POST',
url:'http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr='+mail,
dataType:'someData',
success: function(data) {
if(data === '# rc=0, count=0, message=Success') {
console.log(data);
}
}
});
<?php
$users[]=$row;
}
?>
});
</script>
<?php
echo json_encode($users);
?>
Just Remove dataType:'someData', from your code because it always request and response in json so you dont have to declare separately.

How do get php array in javascript variable

I am using following code .
<?php
$dbhost = 'localhost';
$dbuser = '****';
$dbpass = '******';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mytable';
mysql_select_db('sujeet_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['firstname']} <br> ".
"EMP NAME : {$row['lastname']} <br> ".
"EMP SALARY : {$row['doj']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
to get data from db . But I want to store these data in JavaScript variable for future use. Like var users=$row; but it is not working.
You can do this by putting your mysql result in json format and print it with script tag to use it in javascript like:
<script>
var result = '<?php echo json_encode($row);?>';
</script>
you could do this by assigning inside script tag here is how.
<script>
var spge = '<?php echo json_encode($row); ?>';
alert(spge);
console.log(spge);
</script>

PHP Coding to Connect MYSQL Issues

I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:
?php
$username = "name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Not connected to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>
Can anyone help me to debug this code?
I will be very thankful to you.
Try this one out. It uses MySQLi with error echoing.
<?php
$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con) {
exit("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($con, "SELECT id, model,year FROM cars");
if (mysqli_error($con)) {
exit("Error: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($result)) {
echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}
mysqli_close($con);
First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.

i am developing a website using php and mysql,in this website

i want to fetch data from my database which is linked to the website,i have created a search box,whenever i enter a particular value in search box,it should display all the related content from the database.i have done the following code,it is not fetching the data from the database,it just shows a blank screen.
<?php
define('db_name','njgh');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
session_start();
$link=mysql_connect(db_host,db_user,db_password);
if(!$link)
{
die('couldnot connetc:'.mysql_error());
}
$db_selected=mysql_select_db(db_name,$link);
if(!$db_selected)
{
die('cant connect to db');
}
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM database WHERE Site_ID = '$value'";
$result = mysql_query($qry);
print_r($result);
mysql_query function return resource ID not your data , use mysql_fetch_array, mysql_fetch_object to get data
$value = ($_POST['searchtext']);
$result = mysql_query("SELECT * FROM database WHERE Site_ID = '$value'");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_* has been removed entirely as of PHP 7.0. Prevent SQL injection and use the mysqli statement class.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "njgh";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['searchtext'];
/* create a prepared statement */
if($stmt = $conn->prepare("SELECT * FROM database WHERE Site_ID =?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $value);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['db_table_field_name'];
}
//or
$row = $result->fetch_assoc();
print_r($row);
} else {
}
/* close statement */
$stmt->close();
}
/* close connection */
$con->close();
?>
The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.
Hope this will work for you......
<?php
define('db_name','sports');
define('db_user','root');
define('db_password','');
define('db_host','localhost');
$link=mysqli_connect(db_host,db_user,db_password,db_name);
if(!$link)
{
die('couldnot connect:'.mysql_error());
}
function clean($str) {
$link=mysqli_connect(db_host,db_user,db_password,db_name);
$str = #trim($str);
if(get_magic_quotes_gpc())
$str = stripslashes($str);
return mysqli_real_escape_string($link, $str);
}
if(isset($_POST['searchtext'])){
$value = clean($_POST['searchtext']);
$qry = "SELECT * FROM cricket WHERE id = '$value'";
$qrydb = mysqli_query($link, $qry);
while($row=mysqli_fetch_array($qrydb)){
$name = $row['name'];
}
echo $name ;
}
?>
<body>
<form method="post">
<input type="text" name="searchtext">
<input type="submit" name="submit">
</form>
</body>

Script not posting information from dropdown to textbox

I am trying to get data from a dropdown and post it to a textbox. But by some reason I dont get any response also the Error message that needs to be shown in the textbox.
First of all, this is my dropdown:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["article_id"]. " | " . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
After selecting a item in the dropdown the scripts needs to paste . $row["name"]. into the following textbox:
<input type="text" class="form-control" id="product11" name="product11">
The jquery script that I am using to paste the name is the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information
console.log("getProduct1 before ajax", jQuery('#product1').val());
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'product1' : jQuery('#product1').val()},
success: function(response){
// and put the price in text field
console.log("getProduct1 after ajax", jQuery('#product1').val());
jQuery('#product11').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script uses the following PHP script that connects with the database and retrieves the relevant information:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
$product11 = isset($_POST['product11'])?$_POST['product11']:'';
$query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['product11'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo "Error";
}
}
?>
When I run the script by selecting an option in the dropdown, nothing is happening. Does anyone know what is wrong with my script?
I am not sure you should query the database again for a value you already retrieved. Something like this should work:
jQuery( document ).ready(function() {
jQuery( "#product1" ).change(function(){
var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
jQuery("#product11").val(name);
});
});
You don't need the javascript/jQuery command in the HTML

Categories