searchfunction with JQuery AJAX - php

So Im designing a searchfunction for the backend of a website and Im doing so with AJAX.
So far if you press the "Members" Button it gets the relevant info from the database and displays the members in a table. So far so good.
Now I added a form above the div in which it displays the table:
<form id="searchmember" method="post">
<input type="text" name="searchm" placeholder="Look for a Member!"/>
<input id="search" type="submit" value=">>" name="search"/>
</form>
<div id="eachTable">
And added a function into my JQuery that reacts when the "search" button gets pressed:
$("#search").click(function(){
if(ifIssetData == 1){
var searchm = $('input[name="searchm"]').val();
$.post('/website/administrator/components/com_backend/searchPerson.php', 'val=' + $(searchm).val());
$.ajax({
async: true,
dataType: 'json',
url: '/website/administrator/components/com_backend/searchPerson.php',
error: function(data2, error2, errorThrown2){
alert(JSON.stringify(data2));
alert(error2);
alert(errorThrown2);
},
success: function(data2,status)
{
createTableByJqueryEach2(data2);
},
});
The createTable function is designed to take the data, put it into a table and display that table in the eachTable Div.
So you see it posts searchm to the php file where the following happends:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/website/dbConnection.php');
$searchtrue = $_POST['val'];
$query = "SELECT Titel, Vorname, Nachname, Unternehmen, Gruppe FROM mitglieder WHERE Titel LIKE '%$searchtrue%' OR Vorname LIKE '%$searchtrue%' OR Nachname LIKE '%$searchtrue%' OR Unternehmen LIKE '%$searchtrue%' OR Gruppe LIKE '%$searchtrue%'";
function filterTable($query)
{
$filter_Result = mysqli_query($GLOBALS['connect'], $query);
return $filter_Result;
}
$searchresult = filterTable($query) or die("Tabelle kann nicht angezeigt werden");
$data2 = mysqli_fetch_all($searchresult);
echo json_encode($data2);
?>
So now that you have the code, the Issue. When I press the "search" button the page just reloads and nothing happens. I assume the PHP File doesnt receive the POST? But why? The html is very simple so Im sure that works. The PHP should work but Im not sure since I always had a difficult time getting JQuery and PHP Files to work together.
Anybody know where my issue lies?
edit: I thought Ill just add the function in case the issue lies there
function createTableByJqueryEach2(data2)
{
var eTable2="<table><thead><tr><th colspan='5'>Created by for loop</th></tr><tr><th>Titel</th><th>Vorname</th><th>Name</th><th>Unternehmen</th><th>Gruppe</th</tr></thead><tbody>"
$.each(data2,function(index2, row2){
// eTable += "<tr>";
// eTable += "<td>"+(data2)[i]['Titel']+"</td>";
// eTable += "<td>"+(data2)[i]['Vorname']+"</td>";
// eTable += "<td>"+(data2)[i]['Name']+"</td>";
// eTable += "<td>"+(data2)[i]['Unternehmen']+"</td>";
// eTable += "<td>"+(data2)[i]['Gruppe']+"</td>";
// eTable += "</tr>";
eTable2 += "<tr>";
$.each(row2,function(key2,value2){
eTable2 += "<td>"+value2+"</td>";
});
eTable2 += "</tr>";
});
eTable2 +="</tbody></table>";
$('#eachTable').html(eTable2);
}

Your form is getting submitted as you have a submit input, and it has no action, so it's refresing.
You can change your form to a div or use this:
$(document).ready(function() {
$('#searchmember').on('submit', function(e){
e.preventDefault();
});
});
Also, I created this file and it's working nice:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="searchmember" method="post">
<input type="text" name="searchm" placeholder="Look for a Member!"/>
<input id="search" type="submit" value=">>" name="search"/>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#searchmember').on('submit', function(e){
e.preventDefault();
});
});
$("#search").click(function(e){
var ifIssetData= 1;
if(ifIssetData == 1){
var searchm = $('input[name="searchm"]').val();
$.post('/website/administrator/components/com_backend/searchPerson.php', 'val=' + $(searchm).val());
$.ajax({
async: true,
dataType: 'json',
url: '/website/administrator/components/com_backend/searchPerson.php',
error: function(data2, error2, errorThrown2){
alert(JSON.stringify(data2));
alert(error2);
alert(errorThrown2);
},
success: function(data2,status)
{
createTableByJqueryEach2(data2);
}
});
}
});
</script>
</body>
</html>

You don't need to use a form with AJAX.
If you replace the form with a div, it will resolve the problem.
When you "submit" the form, it tries to post the data somewhere.
Since you've not supplied a URL, it reloads.

Related

AJAX send public static function

I want to insert a like into the database, but I want this on multiple pages. I crated a page where I insert the likes and I included this page on all the other pages.
It works, but now every time I like, the page is reloading. I thought I could fix this with AJAX, but I couldn't find a solution.
Index.php:
include_once('Post.php');
if(isset($_GET['postId'])) {
Post::likePost($_GET['postId'], $userId);
}
//Here sql to select postText, postId...
//Here echo the post
<form action="index.php?postId='.$postId.'" method="post">
<input type="submit" name="like" value="Like">
<input type="submit" name="unlike" value="Unlike">
</form>
Post.php:
class Post {
public static function likePost($postId, $likerId) {
//select database and check if user already liked post. If yes: -1 like if no: +1 like
}
}
Does anyone know if I can use AJAX to send the Post::likePost($_GET['postId'], $userId); so I can like a post without refreshing?
This is how you can try it. the code is well commented
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$(".like, .unlike").click(function(){
var postId= 1;
//var post1 = $('#postId').val();
var id_likeunlike = this.id; // Getting Button id for like or unlike
var userId= 101;
var datasend = "postId="+ postId + "&id_likeunlike=" + id_likeunlike + "&userId=" + userId;
// display a loading image when sending ajax request
$('#loader').fadeIn(400).html('<br><span class="well"><img src="loader.gif" align="absmiddle"> Please Wait, Your Data is being Submitted</span>');
$.ajax({
type:'POST',
url:'post.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#loader').hide();
alert('success');
$('#listpost').fadeIn('slow').prepend(msg);
}
});
});
});
</script>
</head>
<body>
<div id="loader"> </div>
<div id="listpost"> </div>
<input type="submit" id="like" class="like" name="like" value="Like">
<input type="submit" id="unlike" class="unlike" name="unlike" value="Unlike">
</body>
post.php
<?php
$postId = intval($_POST['postId']);
$id_likeunlike = strip_tags($_POST['id_likeunlike']);
$userId = strip_tags($_POST['userId']);
if($id_likeunlike=='like'){
echo "like success";
}
elseif($id_likeunlike=='unlike'){
echo "unlike success";
}
else{
echo "Error occured";
}
?>

Php echo button onclick get id

I hava a dynamic list, loading from database in my php page.This list also have a delete button. When i click this button i need to get id of this button and delete from database that line with php code.
$dbh = new PDO("sqlite:database.sdb");
$sql ="SELECT * FROM clip";
foreach ($dbh->query($sql) as $row)
{
print 'Id: '. $row['id'] .'<br />';
echo '<input type="submit" id="'.$row['id'].'" value="delete" name="del">';
}
also this is my final code for button click;
$dbh->exec("delete clip where id='in here should be button id'");
How can i connect with this two code. Thanks already.
Given the level of your question I am assuming you are unfamiliar with jQuery and AJAX, but you should research both.
For a simple solution not using these you could do as follows:
Change the output to be <input type="button" id="'.$row['id'].'" value="Delete" onclick="do_delete(this.id)">;
Then you need a php script on the server side to handle the delete function, e.g. yourhandler.php
<?
//connect to DB here
if ($_POST['id']) {
$sql = "delete from clip where id=:delete_id";
$stmt = $dbh->prepare($sql);
$stmt->execute([':delete_id'=>$_POST['id']]);
}
?>
Then on the client side you need a form which submits when the button is clicked. Here is an example form code:
<form action="yourhandler.php" method="post" id="myform">
<!--Your PHP script which creates buttons-->
<input type="hidden" value="" name="id" id="delete_id">
</form>
<script>
function do_delete(which) {
var x = document.getElementById('delete_id');
x.value=which;
document.getElementById('myform').submit();
}
</script>
You can use this working jquery template for your task. It binds to all inputs that has a name="del".
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('input[name="del"]').on('click', function() {
alert('button id is '+$(this).attr('id'));
var button_id = $(this).attr('id');
$.ajax({
method: 'post',
url: "delete.php",
data: {'did':button_id},
dataType: "html",
success: function(result) {
alert(result);
}
});
});
});
</script>
In your PHP delete file, you can retrieve the delete id via $_POST['did'].

i want to do some functions with button. i want when i click on button it will be show result. result comes from database

i'm new in PHP i don't know howto use this function...output is a button but when i click on button function not run. i want to get data from database.
<?php include('config.php');
if (isset($_POST['submit'])) {
$sql = "SELECT book_name from books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "book name: " . $row["book_name"]. "<br>";
}
} else {
echo "0 results";
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<form action="check.php" method="post">
<input type="submit" name="btn">
</form>
</body>
</html>
Just change isset($_POST['submit']) by isset($_POST['btn']).
When you submit your form, you send all the input name with $_POST method.
Here you have only ONE input with name = 'btn'.
I do this test :
<?php
if (isset($_POST['btn'])) {
echo 'IT WORKS !';
}
?>
And it works for me, after clicking on "Valider" I got my echo :
Here is an example of how you can try to do it using jQuery and Ajax. I tried to explain how it works and made an example that edit your book list without reloading the page on submit. Hope it helps !
$(document).ready(function() {
// When the form with id 'get_book_list' is sumbit, I will do something :
$("#get_book_list").on('submit', function(e) {
e.preventDefault();
// This is how an ajax call looks like (one example) :
// $.ajax({
// type: "POST", // the method you will use to send the data
// url: "yourfile.php", // the php file you want to call
// data : /* the data you want to send in your php file */,
// dataType: "json", // the data type you want to receive from the php file
// success: function(response){
// // Do something if the ajax call works : here you will edit your book list
// // 'response' is what the php will return, here imagine it's a JSON (dataType = 'json')
// },
// error: function(x,e,t){
// // Do something if the ajax call return error
// }
// });
//I will do the same but without the Ajax :
// 1/ Imagine you are in the success part of the ajax call
// 2/ This is the "response" you get from the php after the select :
var response = [{"book_name" : "title1"}, {"book_name" : "title2"}, {"book_name" : "title3"}];
// 3/ Now just edit your book_list to get what you want :
// I will build a list with each title
var book_list = "<ul>";
$.each(response, function(key, book) {
book_list += "<li>"+book.book_name+"</li>";
});
book_list += "</ul>";
// I add my list in my div
$('.book-list').html(book_list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="book-list">
<!-- here you will update the list of book -->
</div>
<form action="" method="post" id="get_book_list">
<input type="submit" name="btn">
</form>
</body>
</html>
your form actions says "check.php". As a result, when you hit the submit button, you get redirected to check.php page.
your form should simply be like
<form action="" method="post">
<input type="submit" name="btn">
</form>
when action="", the if part of your php will get executed for your current case
isset($_POST['submit']) is false, you should submit some info. you can add <input type="text" name="submit" value="1" />, lets your form have info.

How to use different pages for form input and results using AJAX

So, I have a search form in a php page (top.php) which is an include for the site I'm working on, one php page where all the mySQL stuff happens and the results are stored in a variable and echoed (dosearch.php) and lastly a php page where the results are displayed in a div through jQuery (search.php). This is the javascript code:
$(document).ready(function(){
$('#search_button').click(function(e) {
e.preventDefault();
var searchVal = $('#search_term').attr('value');
var categoryVal = $('#category').attr('value');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: "search_term=" + searchVal + "&category=" + categoryVal,
beforeSend: function() {
$('#results_cont').html('');
$('#loader').html('<img src="layout/ajax-loader.gif" alt="Searching..." />');
if(!searchVal[0]) {
$('#loader').html('');
$('#results_cont').html('No input...');
return false;
}
},
success: function(response) {
$('#loader').html('');
$('#results_cont').html(response);
}
});
});
});
The #search_term and #category fields are in top.php, the other divs (#loader and #results_cont) are in search.php. How would I go by in order to make the form submit and display the results in search.php from the top.php without problems? It works perfectly if the form and javascript are in search.php but I can't seem to separate those and make it work. What am I doing wrong?
PS. Sorry if I'm not clear enough, am at work, really tired. :(
SPLITTING:
<? include('functions-or-classes.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<? include('js-script.php'); ?>
</head>
<body>
<? include('results-div.php'); ?>
<? include('search-form.php'); ?>
</body>
</html>
You should just respect this order then you can split the code in different pieces and include it into your main php file;
PS: peraphs your code should look like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var searchVal = $('#search_term').val();
var query = $(this).serialize(); // search_term=lorem&category=foo
if (!searchVal) {
$('#results_cont').html('No input...');
} else {
$('#results_cont').html('<div id="loader">'+
'<img src="layout/ajax-loader.gif" alt="" /><div>');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: query,
success: function(response) {
$('#results_cont').html(response);
}
});
}
});
});
</script>
</head>
<body>
<form id="search-form">
<input type="text" id="search_term" name="search_term" />
<select id="category" name="category">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input type="submit" name="search_button" />
</form>
<div id="results_cont"></div>
</body>
</html>
you can make your search_button redirect to your search.php an do the work when the pages is loaded instead of doing it on the click event.
and use $_GET['Search'] on the search page
and your url should look like this
/search.php?Search=1337

Jquery Post + run php file > hide the form > give message

here is my code about jquery post. I can't make it work somehow. I spent hours :( what I miss here?! when I run the code, It loads same page :(
I want it to run the php code under
query.php and hide the contact form
and give "thanks!" message at send
submit button click. (with no page
loading)
appreciate helps!
PHP Form
<form id="commentForm" name="contact" method="post" action="">
<ul id="contact-form">
<li><label>Full Name: *</label><input type="text" name="full_name" class="txt_input required" /></li>
<li><input type="submit" value="Send" id="btnsend" name="btnsend" class="btn_submit" /></li>
</ul>
</form>
SCRIPT
$(function() {
$("#btnsend").click(function() {
var dataString = 'fullname='+ escape(full_name);
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
return false;
});
});
Your problem lies in: var dataString = 'fullname='+ escape(full_name);
Try: var dataString = 'fullname='+ escape(document.contact.full_name.value);
Eg:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#btnsend").click(function() {
var dataString = 'fullname='+ escape(document.contact.full_name.value);
$.ajax( {
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>").fadeIn(1500, function() {
$('#contact-form').append("");
});
}
});
return false;
});
});
</script>
</head>
<body>
<form id="commentForm" name="contact" method="post" action="">
<ul id="contact-form">
<li><label>Full Name: *</label><input type="text" name="full_name" class="txt_input required" /></li>
<li><input type="submit" value="Send" id="btnsend" name="btnsend" class="btn_submit" /></li>
</ul>
</form>
</body>
Make sure query.php exists though else it won't execute the call back function at success.
Also make sure you click the button and not press the ENTER key as that will submit the form normally (you have only defined an event handler for click not keypress)
You can preventDefault on the button click or return false on the form's submit event:
$(function() {
$("#btnsend").click(function(e) {
e.preventDefault();
var full_name = $('input["name=full_name"]').val();
var dataString = 'fullname='+ full_name;
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
});
});
or:
$('#commentForm').submit(function() {
return false;
});
Try:
$(function() {
$("#btnsend").click(function() {
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: { fullname: $('input[name=full_name]').val() },
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
return false;
});
});
I think that you have at least 3 problems here. First, you are referencing full_name as if it were a variable. I believe this is causing a javascript error which aborts the function and allows the default action (post) to proceed. Second, you probably need to encode ALL of the form parameters, including act. This is may be causing an invalid URL to be sent and thus the action appears not to have been invoked -- you can check this by looking at the request that is sent with Firefox/Firebug. Third, you are attempting to replace the contents of a list with a paragraph element. This is invalid HTML. I'd replace the entire list with the paragraph (and I don't get what appending an empty string does at the end so I've omitted it).
Note I've changed this to work on the submit event of the form -- so it won't matter how it's submitted. Also allows me a little jQuery niceness in not having to look up the form again.
$('#commentform').submit(function() {
var $this = $(this);
$.ajax({
url: "query.php",
data: { 'act': 'contact', 'full_name', $('input[name="full_name"]').val() },
success: function() {
$('#contact-form').remove();
$this.hide().html("<p>thanks!</p>").fadeIn(1500);
}
});
return false;
}
This is my way to call PHP function directly via jQuery
// in html file
<script language="javascript">
$.post("thisisphp.php",{ func:"true", varbl: 'valu2' },function(data) {
$('.thisdiv #subdiv').html(data);
});
</script>
PHP file thisisphp.php
<?php
// include connection creating file.
require_once("database.php");
$db = & new Database();
function getDateAppointments($varible1, $varible2, $db) {
$q_appointment = "SELECT * FROM `tbl_apoint` WHERE ap_date = '".$varible1."'";
$s_appointment = $db->SelectQuery($q_appointment);
while($r_appointment = mysql_fetch_array($s_appointment))
{
echo '<div id="appoinment">'.$r_appointment['ap_title'].'</div>';
}
}
/* This function for set positions of the day */
switch($_POST['func']) {
case 'true':
getFunc1($_POST['varbl'], 'S0001', $db);
break;
default:
getFunc2($_POST['varbl'], 'S0001', $db);
}
?>
Can this help you?
PS: you can put your hidding and showing form script inside onSucces and onError functions.

Categories