PHP/jQuery Instant Search Not Working - javascript

I'm trying out a tutorial to learn how to do instant search with PHP/jQuery. I can't seem to find why this code won't work. This search was working before when I had the PHP in the same file as the index, but when I moved it to another file, it stopped working. I keep getting this console error message with each keystroke: ReferenceError: Can't find variable: $_POST. Any help would be deeply appreciated.
index.php file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset-utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function searchkey() {
var searchTxt = $("input[name='search']").val();
$_POST("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchkey();">
<input type="submit" value="Search">
</form>
<div id="output"></div>
</body>
</html>
search.php file (same location as index.php)
<?php
$connection = mysqli_connect('localhost','root','root','LBD');
$output='';
if(isset($_POST['searchVal'])){
$searchkey= $_POST['searchVal'];
$searchkey=preg_replace("#[^0-9a-z]#i", "", $searchkey);
$query = mysqli_query($connection,"SELECT * FROM members WHERE ownerName LIKE '%$searchkey%' OR companyName LIKE '%$searchkey%'") or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output="There was no search result!";
}
else{
while($row=mysqli_fetch_array($query)){
$oName=$row['ownerName'];
$cName=$row['companyName'];
$output .='<div>'.$oName.'<br/>'.$cName.'</div>';
}
}
}
echo ($output);
?>

Looks like you've used the PHP $_POST in your script..
Try to use:
$.POST

Try this
$.ajax({
url: "search.php",
type: 'POST',
data: {
searchVal: searchTxt
},
})
.done(function(output) {
$("#output").html(output);
});

Related

jquery add 1 to variable on click then insert to database

I want to have 2 buttons on a page. If u click button "addMe", then I want to add 1 to a variable? (theCount). The other button (InsertDB) I want to add "theCount" into my db.
Im able to add data to my db, but not "theCount", probly because its a "div id" and I dont know how to do it. I have 3 files: index.php, addscript.js and insert.php
Here is my script:
index.php:
<?php
include "insert.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add 1 on click, then add sum to db</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="addMe">Add 1</button>
<div id="theCount"></div>
<form method="post">
<button id="InsertDB">Add to DB</button>
</form>
</body>
</html>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script src="addscript.js"></script>
addscript.js:
var counter = 0;
$(document).ready(function() {
$("#InsertDB").click(function(){
var theCount= $("#theCount").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "theCount=" + theCount,
success: function(data) {
alert("Added to DB");
}
});
});
$("#addMe").click(function(){
counter++;
$("#theCount").text(counter);
});
});
insert.php:
<?php
include "db.php";
$theCount=$_POST['theCount'];
$sql = "INSERT INTO `mat`( `polse`)
VALUES ('$theCount')";
if (mysqli_query($conn, $sql)) {
echo "Craig is Satoshi";
}
else {
echo "Error";
}
mysqli_close($conn);
?>
#theCount is a <div>:
<div id="theCount"></div>
And a <div> doesn't have a value, so this won't work:
var theCount= $("#theCount").val();
Instead, get the text of the element:
var theCount= $("#theCount").text();
Much in the same way that you already set the text of the element:
$("#theCount").text(counter);

PHP fails to get $_POST from JS

I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>

send information to database without having page reload

I have a site where you type into a text box and it will send what I wrote to my database.
I have been stuck with my page having to reload which is very troubling in my case. i am not familiar with ajax but i have heard it can be used to complete this task. i have 2 files one is called demo.php this sends the information to the server and at this time has a header that redirects me back to that page which i don't want.
I want to be able to keep sending things data to the sever without the page reloading. the other page is the index.php this is were i right into the text box and send the text to my database both files are listed below.
this is the demo.php
<?php
header("Location: http://mywebsite.com");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "working";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
this is the forum on index.php were i enter the information and send it. i need it to stay on that page and not reload in any way.
<form action="demo.php" method="post" />
<p> <input id="textbox" type="text" name="firstname" placeholder="Enter What You Want Your Message To Be" /></p>
<input id="textbox1" type="submit" value="Submit" />
</form>
my second attempt at index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="button" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
});
</script>
</html>
You can have two files/pages for your purpose:
1. Form page
2. Ajax processing page where you request values will be inserted into your database.
Add this to your head tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
Steps to utilize ajax:
1. Include jquery library in form page
2. Include html form
3. Save values from ajax, that means process that ajax
HTML form suppose to be like this:
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
Ajax call:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
ajax_target.php handles formData, its validation and insertion to database.
your html/index form consists
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="demo.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
</script>
</html>
your demo.php includes
<?php
//your db insertion goes here.
echo "inserted successfully";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name ="send" value="send" >
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function(){
var options = {
beforeSend: function () {
if (!confirm('Are you sure to submit ?')) {
return false;
}
},
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
};
}
$('#ajax-form').ajaxForm(options);
});
</script>
</body>
</html>
updated your index.php

Get responses from php (SweetAlert)

I want to make form html look like this :
<script>
function name()
{
var name = $('#name').val();
var url_send = 'send.php';
$.ajax({
url : url_send,
data : 'name='+name,
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
}
</script>
<script src="assets/bootstrap-sweetalert.js"></script>
<script src="assets/sweetalert.js"></script>
<link rel="stylesheet" href="assets/sweet-alert.css">
<form action="#" method="post">
<label>Name</label>
<input type="text" name="name"><br>
<input type="submit" onclick="name();">
<div id="result"></div>
and this is send.php
<?php
$name = $_POST['name'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
And the problem is,how i show SweatAlert modal,when result of php is Success Sweatalert will show Success Modal.And when failed it will show Failed Modal ?
Now what must i edit to my script?
I hope you are expecting code with jquery ajax;
See the code below;
index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<link rel="stylesheet" type="text/css" href="sweetalert-master/dist/sweetalert.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="sweetalert-master/dist/sweetalert.min.js"></script>
<script>
$(document).ready(function () {
$("#submit").on("click", function(e){
e.preventDefault();
var name_val = $("#name").val();
$.post( "send.php", {name_send:name_val}, function(data){
if (data == 'success'){
swal("Good job!", "Nice work!", "success");
return false;
}else{
swal("Here's a message!", "Please type a name");
}
});
});
});
</script>
</head>
<body>
<form>
<label>Name</label>
<input type="text" name="name" id="name"><br>
<input type="submit" id="submit">
</form>
</body>
</html>
send.php
<?php
$name = $_POST['name_send'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
$.ajax({
url : url_send,
data : {name: name},
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
in your ajax code you placed data : 'name='+name, , please have a look at what i did , maybe that helps
Jquery ajax accepts object in data parameter data: {key:value}. In the question we are using string as a parameter to data of jquery ajax

JQuery POST data to php, direct to php, data not exist anymore in php

I passed along data via POST to php using JQuery, but when the page direct to the php file, the POST["createVal"] in php doesn't seem to exit after the call back. I showed this in demo below, notice that the $name is undefined when the callback result is clicked. Any idea how to fix this?
I'm trying to make a function that when the returned result was clicked, html page could redirect to the php page in which user input in html file could be printed out.
HTML file
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<input type="text" id="userinput">
<div id="result">
</div>
</body>
<script>
$("input").keyup(function(){
var input=$("input").val();
$.post("process.php",{createVal:input},function(data){
$("#result").html("<a href='process.php'>"+data+"</a>");
})
})
</script>
</html>
php file(process.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
echo $name;
}
?>
<?php
echo $name;
?>
change
$("#result").html("<a href='process.php'>"+data+"</a>");
to
$("#result").html("<a href='process.php?createVal="+data+"'>"+data+"</a>");
and
process.php
if(isset($_REQUEST["createVal"])){
$name=$_REQUEST["createVal"];
echo $name;
}
Use this Html Code:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
</head>
<body>
<input type="text" id="userinput">
<div id="result"> </div>
</body>
<script>
$("input").keyup(function(){
var input=$("input").val();
$.ajax({
type: "POST",
url: "http://localhost/stackoverflow/process.php",
data: {'createVal': input},
success: function(data){
$("#result").html("<a href='http://localhost/stackoverflow/process.php?createVal="+data+"'>"+data+"</a>");
}
});
});
</script>
</html>
PHP Code:
<?php
if(!empty($_REQUEST['createVal']) || !empty($_GET['createVal'])){
$name = $_REQUEST['createVal'];
echo $name;
}elseif(!empty($_GET['createVal'])){
$name = $_GET['createVal'];
echo $name;
}
return 1;
?>
I have run and checked this too.
localhost: if you are running this code on localhost
stackoverflow: is the folder name, if you have any folder in localhost for it so replace the name by this.

Categories

Resources