Array Post Ajax - javascript

The code I'm working shows all the products and the user assigns the corresponding price to each one through an input. Clicking on a single submit button will update all prices.
The problem is if I put an input for each record the server does not post all the records. Only 500 posts are recorded, not the total. The server does not allow me to modify the php.ini file to change the max_input_vars. This code works but it shows me the array in a single input. How do I make the form submit via javascript and post the entire array in a single input? What other solution can I use?
This is the code:
while ($row = mysql_fetch_array($result_categorias4334x)) {
$precio[] = $row['Precio'];
}
<input type="text" name="precios" value="<?php echo implode(",",$precio); ?>
//POST
if (isset($_POST['ok'])) {
$precios = $_POST['precios'];
$preciosarr = explode(",", $precios);
print_r($preciosarr); }
Before I do that:
while ($row = mysql_fetch_array($result_categorias4334x)) {
$precio = $row['Precio'];
?>
<input type="text" name="precios[]" value="<?php echo $precio; ?>">
<?php
}
But it doesn't post all the records. Only the first 500 records.

Related

Ajax And PHP : Handling Multiple Posts in A Single Page

I am developing a webpage where multiple posts from the Database is shown one by one in a single page much like twitter or facebook.
I need to use Ajax for comments and likes. The comment system should be nested as well.
The problem I am having is each post is having a unique post_id and I need to transfer it through Ajax for inserting the comments into the DB.
The below HTML is inside a PHP for loop for getting the posts from Database. So I have given post_id as every comment element's id to get the unique post comment.
<script>
function addcomment(abc) {
var temp1 = abc;
var post_id = temp1.value; // POST ID
var comment = document.getElementById(post_id).value;
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
post_id:post_id,
comment:comment
},
success: function(response) {
document.getElementsByClassName(post_id).innerHTML = response;
}
});
}
</script>
<div class="comment_section" id="comment_section">
<textarea type="text" id="<?php echo($post_id); ?>" placeholder="comment Here..." value=""></textarea>
<button id="comment_button" value="<?php echo ($post_id); ?>" onclick="return addcomment(this);">Comment</button>
<br>
<span class="<?php echo($post_id); ?>"></span>
</div>
And the addcomment.php looks like this:
<?php
include("connect.php");
$postid = $_POST['post_id'];
$comment = $_POST['comment'];
$sql1 = "INSERT INTO comments (name,comment) VALUES ('$postid','$comment')";
$result = $db->query($sql1);
$sql = "SELECT * FROM comments ORDER BY id DESC LIMIT 0,1";
$result1 = $db->query($sql);
while($row = $result1->fetch_assoc()) {
$post = $row['name'];
$comment_op = $row['comment'];
?>
<?php echo $comment_op; ?>
<br>
<?php echo $post; ?>
<?php } ?>
How can I get the comment when the Comment button clicked and store it in the DB and return the Comment below the comment area using AJAX ?
For display comments on specific post first you create comment section and use
<section id="comments-post_id"></section>
when you successfully add comment via above ajax request code get the response and create comment html and append in your comment section.
$("#comments-post_id").html($response);
make sure you have already create your comment HTML in controller or in ajax file where you get the response.
and for the rendering all post data user inside loop or recursive function to get all comments of your specific post
Need more help feel free and ask :)

A real time commenting system

I am making a news feed something like Facebook and other social media platform. For this, I am making a commenting section for each post on the page. I am trying to make the commenting section live (real time), so that when a comment is posted, the page does not refresh.
I know that the commenting system works because I did a test without real time feature (without the use of any form of javascript code).
The following is my code in brief....i only posted what I believe is necessary based on my issue.
function getposts ()
{
global $con;
$getposts = "SELECT * FROM posts";
if ($result = $con->query($getposts)) {
while ($row1 = $result->fetch_assoc()) {
$postid = $row1['post_id'];
?>
<form action='comments_ins.php' method='post' id='reply'>
<input type="hidden" value="<?php echo $postid;?>"
name="postid"/>
<textarea name="comment" id="comment" class="cmt_form"
placeholder="Type a commmment here..."></textarea>
<input type='submit' name='reply' value='Comment'/>
</form>
<?php
}
}
}
?>
Also, the above script i stored in a file given a name of functions. File is php file.
The following code is stored in a different file that is named as home where the functions file is included:
<?php include("functions.php"); ?>
<?php getposts ();?>
So, as indicated earlier, the above code works well. Now, I have slightly altered the code to make attempts to have the comment system be real time.
The following is the altered code:
function getposts ()
{
global $con;
$getposts = "SELECT * FROM posts";
if ($result = $con->query($getposts)) {
while ($row1 = $result->fetch_assoc()) {
$postid = $row1['post_id'];
?>
<form method='post' id='reply'>
<input type="hidden" value="<?php echo $postid;?>"
name="postid" id="postid" />
<textarea name="comment" id="comment" class="cmt_form"
placeholder="Type a commmment here..."></textarea>
<input type='submit' name='reply' value='Comment'/>
</form>
<?php
}
}
}
?>
//in addition to the java to make it real time
<script type="text/javascript">
$(document).ready(function() {
$(".cmt_form").keypress(function(evt) {
if(evt.which == 13) {
var postid = $("#postid").val();
var body = $("#comment").val();
$.post("comments_ins.php", { postid: postid, comment: body},
function(data) {
$('.log').html(data);
$('#reply')[0].reset();
});
}
});
});
</script>
The above java I included in the same functions.php file but outside of the php tags, not being in any loops. The home file is just the same..no changes.
Finally, the following code is the php file that inserts the comment into the database. File name as seen on previous codes: comments_ins.php
$comment1 = ($_POST['comment']);
$post_id = $_POST['postid'];
global $userId;
$insert1 = "insert into comments (post_id,user_id,comment,date) values
('$post_id','$userId','$comment1',NOW())";
$run1 = mysqli_query($con,$insert1);
The above code works to an extent only:
it's not posting the correct postid value to the database. It's only posting postid 1 even though i commented on another post with a different id number.
Also, it's not inputting the comment into the comment field in the database. I see an empty space..no text.
Finally, the output is some crazy output after posting the comment: some strange numbers and some nonsense.
What have i done wrong?
Please help

Table form dynamically refresh with php and ajax

I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>
change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});
If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.

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']);

Form not posting variables/mySQL Query not searching corrently

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)
coaches.php form
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
<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 name="thisID" type="hidden" value="<?php echo $id; ?>" />
<input type="submit" name="button" id="button" value="Log In" />
</form>
coaches.php js function
<script type="text/javascript">
$(document).ready(function()
{
$(".activity").change(function()
{
var activity=$(this).val();
var dataString = 'activity='+ activity;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".username").html(html);
}
});
});
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
</style>
As the js above shows, the player list is handled via a separate page with a query on it as follows:
<?php
if($_POST['activity'])
{
$activity=$_POST['activity'];
$sql=mysql_query("SELECT id, username FROM stats WHERE activity='$activity'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$username=$row['username'];
$activity=$row['activity'];
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".
coachplayer.php SQL query
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
$targetU = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the player
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM stats WHERE id='$targetU' LIMIT 1");
$playerCount = mysql_num_rows($sql); // count the output amount
if ($playerCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$username = $row["username"];
$position = $row["position"];
$activity = $row["activity"];
$agegroup = $row["agegroup"];
$coach = $row["coach"];
$goals = $row["goals"];
$assists = $row["assists"];
$cleans = $row["cleans"];
$motm = $row["motm"];
$attend = $row["attend"];
}
} else {
echo "Player doesn't exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
?>
As I'm sure you can tell, I'm not too great of a coder, so it's very possible that it's a simply var that needs changing but any ideas where I have gone wrong will be much appreciated.
Thank you in advance.
You are using a form with post method. And the action URL seems quite different
<form id="form1" name="form1" method="post" action="coachplayer.php?id=' .$id. '">
Change it to
<form id="form1" name="form1" method="post" action="coachplayer.php">
and in coachplayer.php. Use
isset($_POST['thisID']
Ok, I admit this is not an answer to your question BUT, to be honest there is no such thing as 'your question' - there are contents of four files each of them with their own problems, and an implicit request to grock all of those 4 files and tell you what does not work and how it should be made to work.
Having said that:
Divide and conquer. Make sure your first script does exactly what needs to be done. Then second, then 3rd and only then 4th.
Use tools: For javascript - Dev Tools or Firebug. For queries - MySQL Workbench
When testing JS use console (here you can try out your js code interactively.
) and source tabs - there you can set breakpoints and follow execution line by line. Look at network tab - there you can see request (headers) and responses.
When debugging PHP comment out all your code and use var_dump every step of the way. I use PHP Storm so that i can debug PHP line by line real time.
And better ask questions that can be described with the least lines of code
PS. You can simulate GET requests by typing url in browser - that way you know whether your server side works or not without relying on unreliable JS
Just a Quick look, but your sql Statement seems wrong. Your sql query will search for the Player with the id '$targetU'. Make sure to enter the variable correctly

Categories