Fill in data from database in multiple divs via ajax request - php

I have 2 divs on my html page. When I press my button I want to fill the div #question1 with the question1 data from my database and the #question2 div with the question2 data from my database. Now the 2 divs are filled with the same data.
This is my html and js code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
"use strict";
$('#button').click(function() {
$.ajax({
url: 'getquestions.php',
success: function(data) {
$('#question1').html(data);
$('#question2').html(data);
}
});
});
});
</script>
<input type="button" id="button" value="Load" />
<div id="question1"></div>
<div id="question2"></div>
</body>
</html>
The php file
<?php
$connection = mysqli_connect("localhost", "root", "" , "mobiledatabase");
$query = "SELECT question1, question2 FROM adult_questions WHERE id=3";
$query_run = mysqli_query($connection,$query);
$query_row = mysqli_num_rows($query_run);
if ($query_row==1) {
foreach ($query_run as $row ) {
echo $question1 = $row['question1'];
echo $question2 = $row['question2'];
}
}
?>

Update your php file.
Create an array like $retArr = array("question1" =>$question1,"question2" =>$question2); in your php file Then convert it in to json using json_encode($retArr) & echo json_encode($retArr) In your ajax response show $('#question1').html(data.question1);
Hope this will help

Try this,
In PHP pass it like,
$question1='';$question2='';
if ($query_row==1) {
foreach ($query_run as $row ) {
$question1 = $row['question1'];
$question2 = $row['question2'];
}
}
echo json_encode(array('question1'=>$question1,'question2'=>$question2));
In Jquery,
$.ajax({
url: 'getquestions.php',dataType:'json',
success: function(data) {
$('#question1').html(data.question1);
$('#question2').html(data.question2);
}
});

Related

AJAX load to another div with variable

Hey Im trying to load another div with passing variable.
Im in the div#main , I want a after click #modifybtn button pass the btn value and load it with another div#modify and working with some query.
im noob for jQuery and ajax, I search in web but cant get solution for this.
please check relevant code and tell me about issue.
here is the div#main #modifybtn button and div#modify
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
</div>
<div id="modify">
<?php
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='{$_GET['id']}' LIMIT 1 ");
?>
</div>
dashcompany.php inside
<div class="contentcm" >
//contentcm.php page load content here
</div>
this is my jQuery, after clicking button alert showing but not redirect to the #modify div
$(document).ready(function(){
$('.contentcm').load('contentcm.php #main');
$('a').click(function(){ //main and modify division in contentcm.php
var clickedLink1 = $(this).attr('id');
$('.contentcm').load('contentcm.php #' + clickedLink1);
});
});
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
});
This will be initial.html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src = "FILE_NAME.js"></script>
</head>
<body>
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
<div id="modify"></div>
</div>
</body>
</html>
Your code in FILE_NAME.js should be like
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
Your js file will load the data from dashcompany.php and load in #modify which is in initial.html file
dashcompany.php
<?php
include_once('connection.php');
$id = $_GET['id'];
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='$id' LIMIT 1 ");
$row = $resultmodi->fetch_assoc();
echo "Name: " . $row["name"];
''' print data whatever you need '''
$conn->close();
?>
REASON:
May be you forgot to print data in dashcompany.php file that's why you are getting blank response from ajax request.
And don't forget to include #modify div in the same html file where #main#modify div exists
You can use as follow code, and I suggest you to use post method
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<button type='button' id="modifybtn" class='btn btn-info' value="some_value">click here</button>
<div class="" id="modify"></div>
<script type="text/javascript">
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
//alert(id);
$.ajax({
url: 'dashcompany.php',
type: 'post',
data: {'id' : id},
dataType: 'json',
success: function(response) {
//now you can call with column name of data table
$('#modify').html("<P>"+response.column_one_name+"</p><br><P>"+response.column_two_name+"</p>");
}
});
});
</script>
And your dashcompany.php page should like this,
<?php
// $localhost = "127.0.0.1";
// $username = "root";
// $password = "";
// $dbname = "db_304";
//
// $connect = new mysqli($localhost, $username, $password, $dbname);
// // check connection
// if ($connect->connect_error) {
// die("Connection Failed : " . $connect->connect_error);
// }
$id = $_POST['id'];
$sql = "SELECT * FROM vacancy WHERE vc_id = '$id' LIMIT 1 ";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
Hope this will help you.

How to pass data from HTML, to PHP file by Ajax?

I would like to know, how can I pass <select> element from html to PHP file by ajax.
Here is my index.php:
<p>
<form action = "display.php" method="post" enctype="multipart/form-data">
Select:
<select name="chosenOption" id="chosenOption" style="width:100px"">
<?php
include 'dbConnection.php';
$query = $db->query("SELECT id,name FROM products");
while($row = $query->fetch_assoc())
{
echo'
<option value="'.$row['id'].'">'.$row['name'].'
</option>';
}
?>
</select>
Display : <input type="submit" name="display" value="Display">
</form>
</p>
My display.php, where i have ajax method:
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption:chosenOption},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>
And products.php, where i want to pass selected < select > element:
<?php
include 'dbConnection.php';
$chosenOption = $_POST["chosenOption"];
// Display section
$query = $db->query("SELECT cost,description FROM products_info WHERE products_id=$chosenOption);
if($query->num_rows > 0){
while($row = $query->fetch_assoc()){
echo "Actual cost and description: ".$row["cost"]. " ".$row["description"]. ;
}
} else {
echo "No data";
}
?>
I expect that selected option from index.php will be pass to products.php by ajax and display the appropriate message. The current code does not work. Any idea?
You can't refer to $("#chosenOption") in display.php, because the page has been reloaded. You need to use $_POST['chosenOption'], since that was submitted by the form.
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script>
function refresh_div() {
var chosenOption= $('#chosenOption').val();
jQuery.ajax({
url: 'products.php',
type:'POST',
data:{chosenOption: <?php echo $_POST['chosenOption']; ?>},
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
<div class="result"></div>

Why form is fetching all data when i dont give any input?

This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.

how to insert data with ajax and php without page refresh

I real need your help since I'm a beginner in php and Ajax. My problem is that, I can not send data in the database via my appended form in post.php, also when the button of id #reply clicked it sends empty data to database by refreshing the page. When the reply link is pressed I only get the Result of reply link to be shown without other information (name and comment). I need your help to make my appanded form to be able to add/send data to the database without refreshing the page, I also need to disable the form from index.php to make replies when the reply button / link is pressed. Thank you.
post.php
<?php include("config.php"); //inserting
$action=$_POST["action"];
if($action=="addcomment"){
$author = $_POST['name'];
$comment_body = $_POST['comment_body'];
$parent_id = $_POST['parent_id'];
$q = "INSERT INTO nested (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysqli_query($conn, $q);
if(mysqli_affected_rows($conn)==1) { header("location:index.php");}
else { }
}
// showing data
error_reporting( ~E_NOTICE );
function getComments($conn, $row) {
$action=$_POST["action"];
if($action=="showcomment"){ $id = $row['id'];
echo "<li class='comment'><div class='aut'>".$row['author']."</div><div class='comment-body'>".$row['comment']."</div>";
echo "<a href='#comment_fo' class='reply' id='".$row['id']."'>Reply</a>";
$result = mysqli_query($conn, "SELECT * FROM `nested` WHERE parent_id = '$id' ORDER BY `id` DESC");
}
if(mysqli_num_rows($result)>0) { echo "<ul>";
while($row = mysqli_fetch_assoc($result)) { getComments($conn,$row); }
echo "</ul>"; } echo "</li>";
}
if($action=="showcomment"){
$q = "SELECT * FROM nested WHERE parent_id = '".$row['id']."' ORDER BY `id` DESC";
$r = mysqli_query($conn, $q);
while($row = mysqli_fetch_assoc($r)){ getComments($conn,$row); }
}
?>
<!DOCTYPE HTML><head><script type='text/javascript'>
$(document).ready(function(){
$("a.reply").one("click", function() {
var id = $(this).attr("id");
var parent = $(this).parent();
$("#parent_id").attr("value", id);
parent.append(" <br /><div id='form'><form><input type='text' name='name' id='name'><textarea name='comment_body' id='comment_body'></textarea><input type='hidden' name='parent_id' id='parent_id' value='0'><button id='reply'>Reply</button></form></div>");
$("#reply").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){ showComment(); }
});
});
});
});
</script></head></html>
//index.php
<html><head><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function showComment(){
$.ajax({
type:"post",
url:"post.php",
data:"action=showcomment",
success:function(data){ $("#comment").html(data); }
});
}
showComment();
$(document).ready(function(){
$("#button").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
</script></head><body>
<form id="form_comment">
<input type="text" name="name" id='name'/>
<textarea name="comment_body" id='comment_body'></textarea>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
<input type="button" id="button" value="Comment"/>
</form>
<div id="comment"></div> </body></html>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault(); //add this line to prevent reload
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
Here is a simple incomplete ajax example.
FromPage.php
Here is the ajax that I'd use. The variables can be set however you like.
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var name = "John Smith";
$.ajax({
url: 'toDB.php',
type: 'post',
dataType: 'html',
data: {
carArray: cars,
firstName: name
},
success: function(data) {
console.log(data); //Testing
}
});
</script>
toDB.ph
This is the second page - the one that writes the values to the database etc.
<?php
$cars = $_POST['carArray'];
$FirstName=$_POST['firstName'];
//Used to test - it will print out the array
print("<pre>");
print_r($cars);
print("</pre>");
//Do something with $cars array and $FirstName variable
?>

JQuery/AJAX script not sending data to php file?

I am making a question/status posting system using JQuery and Ajax however an error is being displayed "Notice: Undefined index: status in C:\xampp\htdocs\deadline\data.php on line 5" which is my line of code "$var = $_POST['status']; "
My system works as you have to log in to post a question(using sessions) BUT the issue is with my JQuery/AJAX script as the data that I have on homepage.php is not being sent to data.php (from my understanding which is why my index 'status' is undefined).
MY CODE
<?php
include("connection.php");
session_start();
if(isset($_SESSION['user_id']) && $_SESSION['user_id'] != "") {
}
else {
header("location:login.php");
}
$sid = $_SESSION['user_id'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM `users` WHERE id='{$sid}'";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
$fname = $result['fname'];
$lname = $result['lname'];
$time = time();
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = 'status='+status;
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
</head>
<body>
<div id="global">
<form action="" onsubmit="return false">
<textarea id="status"></textarea>
<button id="postbutton">POST</button>
LOGOUT
</form>
<br/>
<br/>
<div id="allstatus">
<!-- SKELETON -->
<div id="status">
<div id="statuspic">
</div>
<div id="statusinfo">
<div id="statusname">JOnathan</div>
<div id="statustext"> this is the question</div>
<div id="statusoption"><button id="likestatus">LIKE</button></div>
<div id="statusoption"><button id="commentstatus">COMMENT</button></div>
<div id="statusoption"><button id="sharestatus">SHARE</button></div>
<div id="statusoption"><button id="statustime">TIME</button></div>
</div>
</div>
<!-- SKELETON -->
</div>
</div>
</body>
</html>
<?php
$var = $_POST['status'];
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'forum';
//connecting
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
} else {
echo " success";
}
$sql = "INSERT INTO `question`(id, question) VALUES ('', '{$var}')";
$result = $conn->query($sql);
if($result) {
echo "inserted successfuly";
}
else {
echo "failed: " . $conn->error;
}
echo " the text: " .$var. " has been added to database.";
?>
HOW IT SHOULD WORK
I want to use JQuery/AJAX on my homepage.php to send data to data.php and that data gets returned back to homepage.php. On success to be displayed in my div #statustext.
Meaning when i write a question in textarea input field the data gets stored in database and retrieved and displayed in my div on the browser.
Please help me thanks..
you should change your script like below. Ajax sends data to url in a serialize manner either you have to use form serialize which will send all the fileds info to your php url other wise if you have to send only one field value then you can do this change
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = {'status='+status};
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
First of all use .val() not .value() when you getting value of your message. Second mistake - is using two id = "sattus". Id of elements must be unique or use class = "" for ident your class of elements.
Don't give same id to more then 1 html element !
In your code :
<textarea id="status"></textarea>
and
<div id="status">
both contains same id ! Please correct it first.Also In your code as Spencer mentioned in his answer that add name attribute with value "status". No doubt as you are using jQuery selector it should pick up correct one,though you can just alert it before sending the request using AJAX.
also set data variable as var data = {status : status};
POST uses name and not id so change this:
<textarea id="status"></textarea>
To this:
<textarea name="status"></textarea>
For the data make sure it's the data for your form, and add method="post" to it so it can send POST data. For example if you gave your form an id of yourForm:
HTML
<form action="" method="post" id="yourForm" onsubmit="return false">
JS
$.ajax({
...
data: $("#yourForm").serialize(),
...
});

Categories