AJAX POST Error 404 (Not Found) Using javascript,mysql,php - javascript

I'm trying to create a live search bar where I type names and I'm getting results from my database.
This is my project structure:
The files I'm using are map.js where I have my ajax call.
My two php files one for mysql connection and one to retrieve the data from the database.
And last my map.hbs where is my search bar.
map.js
function fill(Value) {
//Assigning value to "search" div in "map.hbs" file.
$('#search').val(Value);
//Hiding "display" div in "map.hbs file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "map.hbs" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "map.hbs" file.
$("#display").html("");
}
//If the name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "Post".
method: "POST",
//Data will be sent to "ajax.php".
url: "/php/loadData.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this function will be called.
success: function(html) {
//Assigning result to "display" div in "map.hbs" file.
$("#display").html(html).show();
}
});
}
});
});
db.php
<?php
$con = MySQLi_connect(
"localhost", //Server host name.
"root", //Database username.
"", //Database password.
"covid_database" //Database name or anything you would like to call it.
);
//Check connection
if (MySQLi_connect_errno()) {
echo "Failed to connect to MySQL: " . MySQLi_connect_error();
}
?>
loadData.php
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
//Search box value assigning to $Name variable.
$Name = $_POST['search'];
//Search query.
$Query = "SELECT name FROM pois WHERE name LIKE '%$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display the result.
echo '
<ul>
';
//Fetching result from the database.
// while ($Result = MySQLi_fetch_array($ExecQuery)) {
// ?>
// <!-- Creating unordered list items.
// Calling javascript function named as "fill" found in "map.js" file.
// By passing fetched result as a parameter. -->
// <li onclick='fill("<?php echo $Result['Name']; ?>")'>
// <a>
// <!-- Assigning searched result in "Search box" in "map.hbs" file. -->
// <?php echo $Result['Name']; ?>
// </li></a>
// <!-- Below php code is just for closing parenthesis. Don't be confused. -->
// <?php
// }}
// ?>
// </ul>
?>
map.hbs
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{{!-- Search Bar --}}
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" id="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" oninput="triggerSearch()">Search</button>
<div id="display">
</div>
</form>
<script src="/map.js"></script>

Your server, which you seem to have written in Node.js, does not recognise the URL you are requesting. This would be because you haven't written an endpoint handler for it.
Your options:
Write an endpoint handler in JS that runs the PHP (Node.js is not the ideal for this, but I believe it is possible).
Run a different server which has decent PHP support (such as Nginx or Apache HTTPD.
Rewrite the PHP program in JavaScript
I'd go for the latter myself, mixing server-side languages is usually more complication than it is worth.

Related

how to have different comments from you in different pages

I am creating a website that contains different movies, every movie has a specific id_movie, i have added a comment box where the user can add a comment about the movie, however, every movie i click on, they all show the same comments that have been entered, I want every movie to have its own comments, I will be happy if you can help me with that. thanks
comments.php
<body>
<br />
<h2 align="center"><p >Add Comment</p></h2>
<br />
<div class="container">
<form method="POST" id="comment_form">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment"></div>
</div>
</body>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
add_comment.php
<?php
$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
$error = '';
$comment_name = '';
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $con->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
fetch_comment.php
<?php
//fetch_comment.php
$con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($con, $row["comment_id"]);
}
echo $output;
function get_reply_comment($con, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($con, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>
and here when I click on each movie:
<?php include('header.php');
$qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
$movie=mysqli_fetch_array($qry2);
?>
<div class="content">
<div class="wrap">
<div class="content-top">
<div class="section group">
<div class="about span_1_of_2">
<h3><?php echo $movie['movie_name']; ?></h3>
<div class="about-top">
<div class="grid images_3_of_2">
<img src="<?php echo $movie['image']; ?>" width="180px" height="280px" alt=""/>
<?php include('ratte.php'); ?>
</div>
<div class="desc span_3_of_2">
<p class="p-link" style="font-size:15px">Type: <?php echo $movie['type']; ?></p>
<p class="p-link" style="font-size:15px">Price: £<?php echo date($movie['price']); ?></p>
<p style="font-size:15px"><?php echo $movie['desc']; ?></p>
Watch Trailer
</div>
<div class="clear"></div>
</div>
<?php $s=mysqli_query($con,"select DISTINCT theatre_id from tbl_shows where movie_id='".$movie['movie_id']."'");
if(mysqli_num_rows($s))
{?>
<table class="table table-hover table-bordered text-center">
<?php
while($shw=mysqli_fetch_array($s))
{
$t=mysqli_query($con,"select * from tbl_theatre where id='".$shw['theatre_id']."'");
$theatre=mysqli_fetch_array($t);
?>
<tr>
<td>
<?php echo $theatre['name'].", ".$theatre['place'];?>
</td>
<td>
<?php $tr=mysqli_query($con,"select * from tbl_shows where movie_id='".$movie['movie_id']."' and theatre_id='".$shw['theatre_id']."'");
while($shh=mysqli_fetch_array($tr))
{
$ttm=mysqli_query($con,"select * from tbl_show_time where st_id='".$shh['st_id']."'");
$ttme=mysqli_fetch_array($ttm);
?>
<button class="btn btn-default"><?php echo date('h:i A',strtotime($ttme['start_time']));?></button>
<?php
}
?>
</td>
</tr>
<?php
}
?>
</table>
<div id='display_comment'></div>
<?php
}
else
{
?>
<h3>No Show Available</h3>
<div id='display_comment'></div>
<?php
}
?>
</div>
<?php include('related-movies.php');
?>
</div>
<div class="clear"></div>
</div>
<?php include('comments.php'); ?>
</div>
</div>
<?php include('footer.php'); ?>
I'll try my best, but there is a lot to cover.
comments.php
//add the target files URL as the form's action
<form method="POST" id="comment_form" action="add_comment.php" >
//add movie to the form, that way when we insert the comment we know what its for
<input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />
//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data){
//...
})
}
//move this below the function definition
load_comment();
add_comment.php
//add movie id here to match what is in the form above
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
// add ':movie_id' => $_POST['movie_id'] to the array you have there for
// $statement->execute([ ....]). The arrays below go the same way
//add those to $statement->execute() for there respective DB calls,
You had the movie in the FIELDS part of the insert, but not the VALUES, which is probably an SQL syntax error. You may not have seen an actual error because this is called with AJAX so it would just break on the client side. You could look in the browser debug window > network [XHR] requests and look at the response. There you would probably find it or you may simply get a 500 error from the server.
fetch_comment.php
//add movie id here to match what is in the AJAX fetch comment call
SELECT * FROM tbl_comment
WHERE parent_comment_id = :parent_comment_id AND movie_id = :movie_id
ORDER BY comment_id DESC
//for execute add
['parent_comment_id'=>0, 'movie_id'=>$_POST['movie_id']]
Important prepare this query properly
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
So it should be like this:
$query = "SELECT * FROM tbl_comment WHERE parent_comment_id = :parent_id";
//then add this to execute ['parent_id' => $parent_id]
mainpage.php (not sure the name on this one)
In the last unnamed code chunk you are using mysqli but above your using PDO it's better to use one or the other, personally I prefer PDO, its just better API wise. You are also not preparing these (so convert these to PDO). Using both just adds unnecessary complexity to your application (I think there were 2 of theses in there):
$qry2=mysqli_query($con,"select * from tbl_movie where movie_id='".$_GET['id']."'");
$movie=mysqli_fetch_array($qry2);
It looks like you include the comments.php into that last page <?php include('comments.php'); ?> So what I would do is where the query is above that I said to fix:
require_once `db.php`; //- create a separate file to do the DB connection for you
//then you can add that to the top of all the pages you need the DB for
include 'header.php'; //no need for the ( ) for any of the include* or require* calls.
/*
require will issue an error if the included file is not found
include will fail silently, for things that are required for your
page to work and not produce errors use require (like the DB)
for things you only ever include once, also like the DB stuff use *_once
then no matter how many *_once calls are stacked from including
the other page you don't have to worry about it.
as above those simple rules give us require_once for the DB.
the other pages I am not sure which would be best.
*/
//localize the movie ID - change any use of `$_GET['id']
$movie_id = isset($_GET['id']) ? $movie_id : false;
if(!$movie_id){
//do something if someone goes to this page with no ?id= in the URL
//you could redirect the page
//you could have a default movie id etc...
}
$statement = $con->prepare('select * from tbl_movie where movie_id=:movie_id');
$statement->execute(['movie_id' => $movie_id]);
$movie = $statement->fetch();
//dont forget to fix the other DB call and remove the MySqli stuff.
Above I suggest using a single file for the DB, in your case it can be quite simple,
db.php
<?php $con = new PDO('mysql:host=localhost;dbname=db_movie', 'root', '');
That is literally all you need then, at the very top of each page you use the DB, simply add this file
require_once 'db.php';
This way if you need to change the password or something like that, you can go to one place named in way that is easy to remember and change it. How it is now, you would have to dig though all your code to change it. In that page your including a file named header.php and it looks like from your MySQLi code that it may have some connection stuff in there. I would remove any MySQLi stuff there too. You want to keep the DB file separate as you may need to include it in the AJAX backend parts and any output from header.php would mess you up.
Summery
What I showed above is a simple example of what you need to do, in that AJAX call This may not be all you need to do, these are just the things that were obvious to me.
You don't have to worry about child comment's movie ID, as they inherit it from the parent comment, which wouldn't exist (on the page) if it had the wrong ID. In your current setup, I would still save it as part of the data. It's just you dont need it to get child comments if you know the parent (which you sort of have to know). I didn't add it into one thing that looked like it was for child comment. You can add it, but as I said above, it's not really needed.
Really the question is way to broad, why isn't my code working kind of question. The only reason I took the effort was that you also took the effort to provide well organized code that is relatively minimal.
So thank you for that.
The last suggestion I would make, is clean up the extra line returns in some of the SQL, and format the TABs a bit better. But that is just a readability issue, I am very picky about formatting my code and some of that could be related to creating an question on SO as it takes a bit of getting used the markdown they use.
Hope it helps you!
Update
thanks for your answer, I really dont know what i should post here and what i shouldnt, and the thing that i dont understand is that: i have a tbl_comment which stores all comments from user and this table include movie_id, and i have another tbl_movie which has movie_id as a primary key, how can i link the movie _id with the tbl_comment so that every comment is stored for a specific movie_id
I will try to explain the flow of your application, with an example. For the sake of this example lets say the movie id is 12 and our main page is www.example.com/movies?id=12:
Inserting a comment
User goes to a url with ?id=12
everything after the ? is called the query string
PHP knows to take the query string and populate the supper global $_GET
so in the main page your movie id is now $_GET['id']
We localize this (make a local variable) at the top of the page with some basic checks. $movie_id = isset($_GET['id']) ? $movie_id : false;
if movie id is set ?id=12 then put it in $movie_id
if its not www.example.com/movies then set $movie_id to false
this avoids some errors if someone goes to the page without that set
At the bottom of the page you include this file <?php include('comments.php'); ?> think of it like pasting that code into this place
In comments.php, which runs when it's included above,
if someone inserts a new comment (submits the form) weve added that same $movie_id into the form with this line
<input type="hidden" name="movie_id" id="movie_id" value="<?php echo $movie_id; ?>" />.
-So now when the form submits to add_comment.php which you need to put in the form's action.
<form method="POST" id="comment_form" action="add_comment.php" >
It will contain the id as $_POST['movie_id'] on that page. The $_POST['movie_id'] is basically the same as $_GET['id'] but the form method tells us its post instead of get. Typically Get is used to retrieve resources, Post is used to modify them.
When PHP runs the above piece of HTML it replaces the <?php echo $movie_id; ?> with it's value of 12 so you get this
<input type="hidden" name="movie_id" id="movie_id" value="12" />
Now On add_comment.php (where the form action takes us) we can take that $_POST['movie_id'] and add that to your SQL used to Insert the comment from the form in #4. into the Database.
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (:parent_comment_id, :comment, :comment_sender_name, :movie_id)
As this is a prepared statement we have the place holder :movie_id in the SQL query. In PDO we can feed that to the PDOStatment object ($statement) you get back from $statment=$conn->prepare($sql) by calling it's execute method or $statement->execute([..other stuff here..., 'movie_id'=>$_POST['movie_id']]).
The query that runs looks like this after PHP is done with it
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name, movie_id)
VALUES (0, 'foo', 'ArtisticPhoenix', 12) <-- see what I did there.
So you see we took the value from the original URL request, added it to our form and then we wait for user action to submit that form with the movie id embedded in it. The when the form submits it calls our add comment page, where we take it out of the Posted data, and feed it into the DB with the rest of the form data for that comment.
The other ones are exactly the same except in those we are using AJAX to submit the data so instead of a form we just add it to the AJAX call. I will give you an example of how that executes.
Showing a comment
This is the same up to #4 above
In comments.php you call load_comment(); "After" defining the function as it doesn't exist tell you do that, so you cant call it before.
This runs your AJAX request $.ajax, for the purposes of this example think of it like a fancy way to do a form. The url is the form action the method is well the method. The data is the form data, the dataType is the type of encoding in this case JSON or Javascript Object Notation. Which is a fancy way of saying structured data, as in PHP its basically an array (or data with nested elements).
The url (action) points us to fetch_comment.php, so when that runs our data: {movie_id : <?php echo $movie_id; ?>}, becomes data: {movie_id : 12}, which gets sent back to server where PHP sees it as $_POST['movie_id']
Similar to the Insert, we use that ID in our SQL query that pulls the parent comments
SELECT * FROM tbl_comment
WHERE parent_comment_id = :parent_comment_id AND movie_id = :movie_id
ORDER BY comment_id DESC
This says "Select all columns From table tbl_comment WHERE parent_comment_id IS 0 and Movie Id is 12" So it will only return comments for movie 12 that are also parents.
in your code you have just $statement->execute(); But you had the parent_comment_id hard coded as 0. This was fin until we needed to add the movie_id Once we did that it makes more senses to make it part of the prepared statement so it reads better. But like the insert, now we have place holder in place of values so we need to take that data and add it to execute for this query.
So $statement->execute(); becomes $statement->execute(['parent_comment_id'=>0, 'movie_id' => $_POST['movie_id']]); Or when PHP is done with it $statement->execute(['parent_comment_id'=>0, 'movie_id' => 12]); which the Database knows to use the keys to match the placeholders and it completes our query.
SELECT * FROM tbl_comment
WHERE parent_comment_id = 0 AND movie_id = 12
ORDER BY comment_id DESC
Then we take the results and send them back to the success handler for the AJAX with echo and in this case add it to the page with this line $('#display_comment').html(data);
So In conclusion
Your code:
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
Correct code (what I said):
//.. in your JS, add the movie id to the fetch comment call
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data){
//...
})
}
load_comment();
What you need to do
//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : <?php echo $movie_id; ?>},
dataType: 'json',
success:function(data)
{
$('#display_comment').html(data);
}
});
}
load_comment();
When PHP completes the above code it sends this to the client (using 12 from our example)
//$movie_id = $_GET['id'] in the main page that included this file.. #2 above
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {movie_id : 12}, //PHP takes the value of $movie_id and puts it here
dataType: 'json',
success:function(data)
{
$('#display_comment').html(data);
}
});
}
load_comment();
Above is what actually runs in the browser
That is pretty much the gist of it. As I said its more beneficial to you to learn how it works. Sure I can post the complete code but I have no way to test it, no way to know if that is all the errors or not. If you learn how it works, you will be better equipped to take on those challenges yourself. I would rather spend 3 or 4 times the effort teaching you how it all works, then to post some code that you have no idea how it works.
Hope that all makes some sense.

Echo JS onclick fill function AJAX not working

I have a search bar with AJAX, MySQL, PHP, and JS. The search bar gives live search results in a div in a list and works in that respect.
My problem is the live search results in the div list when clicked on do not fill the search bar's input. Nothing happens and the list just stays open unless I click out of it. I used to have it working in my old code where when you click on any result it fills the search bar's input, but ever since I rewrote the whole code I can't figure out why the onclick and fill functions aren't working now.
How can I fix this code so that when a user clicks on one of the results in the live search result list it fills the search bar's input?
Here is what I've tried and currently have as my code in the following files:
index.php
<form>
<input type="text" id="search" class="search" data-js="form-text"
placeholder="Search Over 100+ Resources..." autocomplete="off">
<button type="submit" class="Button" value="Submit"><i class="fa fa-
search"></i></button>
<div id="display"></div>
<div id="backspace" style="display:none"></div>
</form>
script.js
//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "index.php" file.
$('#search').val(Value);
//Hiding "display" div in "index.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "indexd.php" file. This function will
be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
$('#display').hide();
$('#backspace').css("display", "none");
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "index.php" file.
$('#backspace').css("display", "block");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "GET".
type: "GET",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
//Assigning result to "display" div in "index.php" file.
$("#display").html(html).show();
}
});
}
});
});
ajax.php
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
if ($ExecQuery->num_rows > 0) {
echo "<ul>";
while ($Result = MySQLi_fetch_array($ExecQuery)) {
echo "<li onclick='fill".$Result['Name']."'>".$Result['Name']."
</li>";
}
echo "</ul>";
}
}
die();
?>
you can use the ` sign instead of the single and double quotation for javascript.
Here you should just update the line 16 at ajax.php file like this.
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."
Complete code
ajax.php file
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
if ($ExecQuery->num_rows > 0) {
echo "<ul>";
while ($Result = MySQLi_fetch_array($ExecQuery)) {
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."
</li>";
}
echo "</ul>";
}
}
die();
?>
JS codes.
//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "index.php" file.
$('#search').val(Value);
//Hiding "display" div in "index.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "indexd.php" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
$('#display').hide();
$('#backspace').css("display", "none");
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "index.php" file.
$('#backspace').css("display", "block");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "GET".
type: "GET",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
if (html == '<ul><li>No Result Found!</li></ul>') {
$('#no-results').css("display", "block");
}else{
//Assigning result to "display" div in "index.php" file.
$("#display").html(html).show();
}
}
});
}
});
});

Incrementing $_SESSION index in jquery

<?php
session_start();
$j=0;
?>
<form class="contact100-form validate-form" action="step-3.php" >
<div class="wrap-input100 validate-input bg1 rs1-wrap-input100">
<div class="contact100-form-btn" id="add_driver">
<span>
Add another Driver
<i class="fa fa-long-arrow-right m-l-7" aria-hidden="true">
</i>
</span>
</div>
</div>
</form>
<script>
$("#add_driver").click(function () {
$( "#add_driver_section").replaceWith( "<div class='wrap-input100 validate-
input bg1 rs1-wrap-input100' data-validate = 'Enter Your First Name'> <span
class='label-input100'>Firstname *</span> <input class='input100'
type='text' name='name[]' placeholder='Enter Your First Name ' <?php
if(isset($_SESSION['name'][++$j])){echo "value='".$_SESSION['name']
[$j]."'";}?> ></div>");});
</script>
$_SESSION['name'] is an array with multiple values. I need to increment the value of $j so as to get a new index of $_SESSION['name'] every time the add_driver is clicked. This code works only the first time. The rest of the time it prints the same value as that in the first time. I am unable to show you the rest of the code or screenshots of the output because of company rules. Please tell me what is wrong with my code and how to acheive what i'm looking for. I only want some method to increment the index. Thank you in advance.
$_SESSION is a server variable, so you can't change it on the client side without interacting with the server. I would recomend you to use AJAX.
When the button is clicked, an AJAX request loads an empty page that increases the $_SESSION variable. (also you have to store $j also as a session variable, so you can have a track of it)
so for example:
in some file called myFile.php, you increment the index and retrieve the name in that index.
<?php
//this file just increases j everytime is loaded
session_start();
if (isset($_SESSION['j'])){
$_SESSION['j']++;
} else {
$_SESSION['j'] = 0;
}
$result['name'] = $_SESSION['name'][$_SESSION['j']];
die(json_encode($result));
then in you button:
$("#myButton").click(function (evento) {
jQuery.ajax({
url: "myFile.php",
dataType: "json",
method: "POST",
data: {},
success: function (data) {
alert("The name[j] is " + data.name)
// do here what you did in your button before
// DONT use PHP echos here, use the data.name variable to access the $_SESSION['name'][$j] value
}
});
});
Remember that PHP is a preprocesor, so when the page loads in the client side, everithing PHP printed is now a constant. so you cannot use the echoed values and make them change.
There is another method, and that is to send all the $_SESSION['name'] variable and use it in the client side. the problem is that if $_SESSION['name'] changes after the user loaded the page, then he won't notice.
So it would be like this:
(not tested, please excuse syntax errors)
<script>
var names = JSON.parse("<?php echo json_encode($_SESSION['name']); ?>");
var count = 0;
$("#add_driver").click(function () {
count++;
alert("now the name you needed is here: " + names[count]) //you have the name in names[count], do what you will
});
</script>

Getting a variable from my form to my parser file via ajax

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

AJAX does not POST results to php page

I'm trying to create a player edit system for an admin section of a football website. The process goes as follows:
Once a coach has logged in on 'coaches.php', they can then choose what coaching session they want to look at via dropdown, which then populates the 'player' dropdown (done via js below)
form on coach-home.php
<form id="form1" name="form1" method="post" action="coach-player.php">
<label>Activity :</label>
<select name="activity" class="activity">
<option selected="selected">--Select Activity Group--</option>
<?php
include('dbconnect.php');
$sql=mysql_query("select activity from coaches where username='$coach'");
while($row=mysql_fetch_array($sql))
{
$activity2=explode(",",$row["activity"]);
foreach ($activity2 as $activity)
echo '<option value="'.$activity.'">'.$activity.'</option>';
} ?>
</select> <br/><br/>
<label>Player :</label> <select name="username" class="username">
<option selected="selected">--Select Player--</option>
</select>
<input type="text" name="pid" class="pid" id="pid" value="<?php echo $pid; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
JS request on coach-home.php
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").click(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "GET",
url: "username.php",
data: dataString,
cache: true,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
username.php
<?php
if($_GET['activity'])
{
$activity=$_GET['activity'];
$sql=mysql_query("SELECT pid, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$pid=$row['pid'];
$username=$row['username'];
echo '<option value="'.$username.'">'.$username.'</option>';
}
}
?>
Once all of this is done, the coach submits the form, taking them to coachplayer.php. This is where the problem begins.
coachplayer.php is a template page, with empty fields filled with echo's, to echo the player details where necessary. A query runs to get the id of the selected player, bring up their details and fill the page. Instead, however, it echos what usually comes up if the query cannot find a matching result via $playerCount as shown below, saying "Player doesn't exist".
coach-player.php Query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['username'])) {
// Connect to the MySQL database
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE username='$puser' LIMIT 1");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$username = $row["username"];
$pid = $row["pid"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
}
} else {
echo "That player does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
The issue here is that whilst it is defined in username.php, the pid does not get sent over and saved when the rest of the form on coach-home sends. I have tried changing from GET to POST with no avail. I have also just tried using the 'username' instead of 'pid' but I get "That player does not exist."; - meaning no variables outside of the ajax request is sending.
What is it that needs to be altered to save and post the data mentioned?
Looking at your code the $username and $pid variables are not being passed to either coach-home.php or coach-player.php, thus when you try to write to the database the parameter $_GET['username'] or $_GET['pid'] is set (because you have provided an input field in your form), but it has no value! and thus there is no player that exists with an empty pid or username.
Also note that in the form you have specified the method as post, but in the php you are referencing the get hash. If you submit by post you access variables with $_POST, submit with get you access with $_GET.
My suggestion is to use the session hash to store the username and pid of the user.
When the user logs in:
$_SESSION['username'] = 'jonnysmith'
$_SESSION['pid'] = '45'
This will mean when you initiate the database query you will just reference the session value instead of the get value for the parameter.
Delete your input field for username/pid in the form.
Call session_start(); in your config.php file to enable the session hash.
Call session_destroy(); when the user logs out to clear the session hash.
Also you will need to logout and log back in for the changes to take effect and the value of username/pid to be stored in the session hash.
Happy hunting!
Your regex is actually replacing your whole username variable with ''
Based on your comment, I've done a test match with the name 'Radamel Falcao' and echo-ed $puser and I got empty string, so apparently, this regex is your problem.
$puser = preg_replace('#[^0-9]#i', '', $_GET['username']);

Categories