Searchbox (AJAX) won't load requested data - php

so I have a problem I can't find the error.
By default the page should load all data and when I hit search, only the requested ones (no refreshing page).
(Even better would be if I could also change the outcome/request by changing the url without having to type in in the input field:
entering url: .../searchpage.php?search=banana --> results for banana
entering url: .../searchpage.php?search=apple --> results for apple
but small steps first.)
Do you have maybe see where my problem is? Or so you know some good pages where I can find solutions/information for my problem? \
A big thankyou in advance!
index.php:
<script src="assets/js/jquery.min.js"></script> //v3.4.1
<section class="wrapper">
<div class="formpost">
<div class="searchpannel">
<input type="text" class="searchBox" name="searchBox" id="searchBox" placeholder="Search..">
<button type="submit" id="searchBtn">SEARCH</button>
</div>
<div id="SearchResult"> <?php include 'startdata.php'?> </div>
</div>
</section>
<script>
$(document).ready(function(){
$('#searchdata').click(function(e){
e.preventDefault();
var searchtext = $('input[name=searchBox]').val();
$.ajax({
type: "POST",
url: "fetchdata.php",
data: {
"search_post_btn": 1,
"searchBox": searchBox,
},
dataType: "text",
success: function (response) {
$("#SearchResult").html(response);
}
})
})
})
</script>
fetchdata.php:
<?php
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, 'ajax');
if(isset($_POST['search_post_btn'])) {
$search = $_POST['searchBox'];
$query = "SELECT * FROM ajaxtest WHERE name LIKE '%$search%' ";
$query_run = mysqli_query($conn,$query);
if(mysqli_num_rows($query_run) > 0){
WHILE ($row = mysqli_fetch_assoc($query_run)) {
echo "<h2>Hallo, my name is ";
echo $row['name'];
echo "<strong>";
echo $row['famname'];
echo "</strong></h2><p> On the list I'm place ";
echo $row['id'];
echo "</p>";
}
}
}
?>

Hi you have to do some modification in your code
$.ajax({
type: "POST",
url: "fetchdata.php",
data: {
"search_post_btn": 1,
"searchBox": searchBox,
},
dataType: "json",
success: function (response) {
$("#SearchResult").html(response);
}
})
----- PHP CODE ----
<?php
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($conn, 'ajax');
if(isset($_POST['search_post_btn'])) {
$search = $_POST['searchBox'];
$query = "SELECT * FROM ajaxtest WHERE name LIKE '%$search%' ";
$query_run = mysqli_query($conn,$query);
if(mysqli_num_rows($query_run) > 0){
$design = "";
WHILE ($row = mysqli_fetch_assoc($query_run)) {
$design .= "<h2>Hallo, my name is ".$row['name']."<strong>".$row['famname']."</strong></h2><p> On the list I'm place ".$row['id']."</p>";
}
print_r(json_encode($design));
die;
}
}
?>

Related

How to show data from mysql using AJAX into text field

Previously I could not know about ajax. therefore I want to ask.
I want to display my wordlist from mysql into a text field but in array. this is the index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "html",
success: function(){
$('').html();
}
});
});
});
</script>
And then this is the process.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "posts";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select wordlist from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('wordlist'=>$row[0]));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I will be very helpful if you can give an answer. Thank you
Change your PHP loop to something like this:
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('wordlist'=>$result));
Then, in your JS, see below
$(document).ready(function() {
$("#display").click(function() {
/*$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "json",
success: function(response){
// use the code below in this area
}
});*/
let response = {
"wordlist": ["This", "is", "the", "return", "from", "your", "server"]
} // this is what the response object will look like in your success function above
let output
// normal comma delimited response
output = response.wordlist.join(",");
// or if you want to keep the quotes
output = JSON.stringify(response.wordlist);
output = output.substr(1, output.length - 2);
// use .val() to set the value of an input
$('#wordlist').val(output);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>

php with ajax in form input data update

Id how I post, I did not understand the logic.
Why doesn't it update? no error message, please help me!
i don't understand much of ajax. :(
. . . .
index.php
<?php
require "header.php";
$con= mysqli_connect("localhost","root","","propanel_001");
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}
$gelen_id=#$_GET['id'];
$sql="SELECT * FROM tb_haber where id='$gelen_id'";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_assoc($result);
?>
<form id="my_form">
<label>Haber Başlığı</label>
<input value="<?php echo $row['haber_title'] ?>" type="text" name="haber_title">
<label>Haber İçeriği</label>
<textarea name="haber_desc" class="ckeditor text-justify"><?php echo $row['haber_desc'];?></textarea>
<button type="submit" name="btn_haber_update">UPDATE</button>
</form>
<script>
$(document).ready(function(){
$("form[id=my_form]").submit( function(up_haber) {
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var form_data = new FormData(this);
SwalUp_Haber(form_data);
up_haber.preventDefault();
});
});
function SwalUp_Haber(form_data){
$.ajax({
url: "update-haber.php",
type: "POST",
data: form_data,
dataType: "json",
contentType: false,
cache: false,
processData: false,
})
.always(function(response_up_haber) {
swal({
title: response_up_haber.titles,
text: response_up_haber.message,
type: response_up_haber.status,
showConfirmButton: false,
timer:3000,
});
});
}
</script>
update-haber.php
<?php
header('Content-type: application/json; charset=UTF-8');
$response_up_haber = array();
$id_haber_up = $_GET['id'];
$haber_title = mysqli_real_escape_string($con, $_POST['haber_title']);
$haber_desc = mysqli_real_escape_string($con, $_POST['haber_desc']);
$query = "UPDATE tb_haber SET haber_title='$haber_title', haber_desc='$haber_desc' where id='$id_haber_up'";
$update=mysqli_query($con, $query);
if ($update>0) {
$response_up_haber['status'] = 'success';
$response_up_haber['titles'] = 'BAŞARILI';
$response_up_haber['message'] = 'Haber başarılı bir şekilde güncellendi..!';
}else{
$response_up_haber['status'] = 'error';
$response_up_haber['titles'] = 'HATA';
$response_up_haber['message'] = 'Bir sorun oluştu ...
<br>Lütfen bu durumu ProPANEL yetkililerine bildirin..!';
}
echo json_encode($response_up_haber);
?>

How to return output on the same page ajax php

I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}

On onblur event ajax get calles but it not returning to the original page

In my code the onblur event ajax method gets called in that it goes to ajaxcarmake.php. It executes the logic correctly but it does not come back to the addcarmake.php page. It also doesn't show me the alert message inside success:
plz give me the answer what i did wrong.
addcarmake.php
<form name="addcategoryfrm" id="addcategoryfrm" action="addcarmake1-process.php" method="GET">
<div style="width:100%;height:auto;float:left;margin-top:50px;">
<div class="txttitle">Car Make Name </div>
<div class="txtinputouter1">
<input type="text" name="name" class="categoryname" onblur="check_carmake(this);"/>
</div>
</div>
<div style="width:100%;height:auto;float:left;margin-top:10px;">
<div class="txtinputouter1" style="padding-left:30%;padding-top:40px;">
<input type="submit" value="Submit"/>
</div>
</div>
<div id="demo"></div>
</form>
Script
<script>
function check_carmake(name) {
$name = name.value;
$.ajax({
type: "GET",
url: 'ajaxaddcarmake.php',
data: {
$name: $name
},
success: function(result) {
if (result == 1) {
alert("Car make name already present");
}
},
error: function(err) {
alert(err);
}
});
}
</script>
ajaxaddcarmake.php
<?php
session_start();
if (isset($_SESSION['username1'])) {
include("../config/database.php");
$name = $_GET['$name'];
$query = "select * from add_car_make where name='$name'";
$result = mysql_query($query) or die(mysql_error());
echo $query;
$rows = mysql_num_rows($result);
if ($rows > 0) {
echo 1;
} else {
echo 0;
}
}
?>
Few things that we have missed .
script
script should like this .
data should send like this
data: {
name: $name
},
not
data: {
$name: $name
},
we were passing '$' in the variable.
<script>
function check_carmake(name) {
$name = name.value;
$.ajax({
type: "GET",
url: 'ajaxaddcarmake.php',
data: {
name: $name
},
success: function(result) {
if (result == 1) {
alert("Car make name already present");
}
},
error: function(err) {
alert(err);
}
});
}
</script>
ajaxaddcarmake.php
Also in this php script , we have small changes.
we have to get variable like this
$name = $_GET['name']; // remove '$' not $name = $_GET['$name'];
<?php
session_start();
if (isset($_SESSION['username1'])) {
include("../config/database.php");
$name = $_GET['name'];
$query = "select * from add_car_make where name='$name'";
$result = mysql_query($query) or die(mysql_error());
echo $query;
$rows = mysql_num_rows($result);
if ($rows > 0) {
echo 1;
} else {
echo 0;
}
}
?>
Hope this will help!

Getting all the content of table and append it using ajax with jquery

I made a simple sample on how to insert using AJAX and retrieving it then append it in a <div> after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.
<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
jQuery:
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>
Your while should create array and then do json_encode
Try below code
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message']
);
}
echo json_encode($data);
exit
Now write your javascript success handler as below
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$.each(data, function(i, item) {
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
});​
}
});
There are several issues you have to fix, but you have to start with returning the same type as expected by the ajax call:
$return = array()
if ($row = mysql_fetch_array($result))
{
$return['username'] = $row['user_name'];
$return['mesg'] = $row['message'];
}
echo json_encode($return);

Categories