Best way to submit multiple input fields jQuery/PHP? - javascript

I'm trying to upgrade my like-system to something more practical.
Currently I have it like Like then in the PHP have something like: if $_GET['like'] is set, then grab the user's ID and the post ID and call a function called like_status($post_id,$user_id);
However, I've been working on something like this:
The main part that shows on the statuses:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script src="https://mysite/stuff/js/global.js"></script>
<input type="hidden" id="postid" value="<? echo $postid; ?>">
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;">Like</span>
The Javascript/jQuery:
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
if (postid != ''){
$.post('https://mysite/stuff/ajax/like.php', {postid: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = data;
});
}
});
and finally,
My like.php script:
<?php
if(isset($_POST['postid']) === true && empty($_POST['userid']) === false){
include $_SERVER['DOCUMENT_ROOT'].'/stuff/init.php';
if(is_liked($_POST['postid'],$_POST['userid']) === true){
unlike_status($_POST['postid'],$_POST['userid']);
echo 'Like';
} else {
like_status($_POST['postid'],$_POST['userid']);
echo 'Unlike';
}
}
?>
My unlike/like functions work fine. I have a working like system now, but it makes the user refresh and everything every time, and it's very inconvenient. I'd like to use this method to automatically update the like button without having to refresh the page or anything. This way, users can like multiple things on the page, and not have to refresh the page every time. I also think it's more secure since the $_GET['like'] can be changed to any id, even if user's aren't friends with other users, or the status doesn't exist.
My issue:
Okay, so whenever I click the like button, nothing happens. I tried this in a separate page as well (changing the type from hidden to text, and manually inputting the data) and it didn't work either. It seems the javascript doesn't execute. I've opened up console in google chrome, and when I click the button, nothing happens. The like doesn't get posted to the database, and the button doesn't get updated.
Can anyone explain what I'm doing wrong? Possibly point me in the right direction to fixing this?
UPDATE
I tried combining the Javascript/HTML in one page to have dynamic variables.
This is what shows up for each status:
<script src="https://mysite/stuff/jquery.min.js"></script>
<script type="Javascript">
$(document.body).on('click','#like-button', function(
var postid<? echo $status_id; ?> = $('input#postid<? echo $status_id; ?>').val();
var userid<? echo $status_id; ?> = $('input#userid<? echo $status_id; ?>').val();
$.post('https://mysite/stuff/ajax/like.php', {postid: postid<? echo $status_id; ?>, userid: userid<? echo $status_id; ?>}, function(data){
document.getElementById('like-button').innerHTML = data;
});
));
</script>
<input type="hidden" id="postid<? echo $status_id; ?>" value="<? echo $status_id; ?>">
<input type="hidden" id="userid<? echo $status_id; ?>" value="<? echo $session_user_id; ?>">
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<?}?></span>
I still can't get it to execute the script.

You can always just use $('#fomrm_id').serialize(), to get all the form fields at once in POST data. It refreshes page because you have to add return false; to the end of jQuery.click event.
If those elements are being created dynamically (or as in your case script is being executed before they are created), you need to set proper .on event, this one is not good, as it binds to the element that may not be there.
Should be rather:
$(document.body).on('click','#like-button', function(){..}); - that will bind it to document body, that is always there, but will check for selector in second argument if it matches.

It's not exactly what I wanted to do, but it's good enough. I managed to get the like button to work/update without refreshing and such. Thanks to everyone for the help if it wasn't for your suggestions I would've never found this out.
<input type="hidden" id="postid" value="<? echo $status_id; ?>"><br>
<input type="hidden" id="userid" value="<? echo $session_user_id; ?>"><br>
<span id="like-button" style="color:red;"><? if(isliked($status_id,$session_user_id) === true){ ?>Unlike<? } else { ?>Like<? } ?></span>
<script>
$('span#like-button').on('click', function(){
var postid = $('input#postid').val();
var userid = $('input#userid').val();
<? if(isliked($status_id,$session_user_id) === true){ ?>
$.get('https://mysite/dash', {unlike: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Like';
});
<? } else { ?>
$.get('https://mysite/dash', {like: postid, userid: userid}, function(data){
document.getElementById('like-button').innerHTML = 'Unike';
});
<? } ?>
});
</script>

Related

How to post both a javascript variable and a html form via $.ajax post?

I posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz

Page is refreshing and query won't take place - Ajax, PHP

function add_comment(ele) {
event.preventDefault();
var username = "<?php echo $current_user; ?>";
var user_id = "<?php echo $current_user_id; ?>";
var post_id = $(ele).data('id');
var comments = $(ele).parent(".comment-section").find(".comment").val();
alert(comments);
if (username == "") {
alert("Please Log in to Star the Post");
window.location = "http://tobbyandscooby.com/log.php";
return;
}
$.ajax({
type: 'POST',
url: 'add_comment.php',
data: {
postid: post_id,
uname: username,
uid: user_id,
comment: comments
},
success: function(response) {
//alert("Successfully Comment is Added! ");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-section">
<textarea id="<?php echo $post_id; ?>" class="comment" value="" data-id="<?php echo $post_id; ?>"></textarea>
<button id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(this);">Comment</button>
<div class="comment-show"></div>
</div>
<?php
include("connect.php");
$username = $_POST['uname'];
$post_id = $_POST['postid'];
$user_id = $_POST['uid'];
$comments = $_POST['comment'];
$sql = "INSERT INTO comments (user_id,username,post_id,comment) VALUES ($user_id,'$username',$post_id,'$comment')";
$result = $db->query($sql);
?>
I am trying to make a comment system with Ajax. I have done similar thing like favourite, down vote, upvote with Ajax. But now with this above code, I couldn't enter the data into the DB and also on clicking comment button the page refreshes even though I have used *preventDefault();
I know I have made some mistake but couldn't debug it. Also please suggest me how to add the entered comment into div .comment-show using the success in ajax.
**NOTE: I could get the alert(comments); working when preventDefault(); function is removed! I have added the XHR requests for other elements which are working fine! **
The problem is the preventDefault().
You now pass this with that function call in onClick.
To solve it, make the button a submit-button by adding <button type="submit" ..
and pass event with your function call: ...onClick="add_comment(event);"
// complete line:
<button type="submit" id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(event);">Comment</button>
But now you need to rewrite pieces of the function, because ele is now the event, not the element anymore:
Change every $(ele) to $('#id')
And obviously in the beginning of the function the variable name for the passed-in event needs to match:
function add_comment(e) { // whatever you wanna name it, e has to be the same
e.preventDefault(); // as this e
Another solution would be to keep the button just a normal button, remove the onClick there, and add onSubmit="add_comment(event);" to your <form..>

AJAX: Replace a div's content with a specific div from the collected data

To me that looks correct, but i'm not experienced with AJAX in the slightest, been stuck at it for hours trying many variations including filter and it's all been useless. This is currently what i have and i can't see anything wrong with it.
What is happening is that no chat messages are showing up like they usually do, if i was to just refresh the page.
What i am simply trying to accomplish is a chat interface if that has any relevance.
Here is a live example of what is happening: http://www.mixpix.eu/chat/chat.php?r=G97NxXy4exbLQPFU
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
dataType: "html",
url: 'chat.php?r=' + <?php echo "'" .$_GET['r']. "'"; ?> ,
success: function(data) {
var trim = $(data).find('.message_window');
$('.message_window').replaceWith(trim);
}
});
}, 1000);
});
Here's the contents of my body tag:
<div class="wrapper">
<div class"inbox_window" id="style-3">
</div>
<div class="message_window" id="style-3">
<table width="100%">
<p class="talking_to"><?php echo getFirstnamebyID($_GET['r']); ?></p>
<?php echo displayMessages(); ?>
</table>
</div>
<form class="submit_form" method="post" <?php echo 'action="chat.php?r='.$_GET['r'].'"' ?>>
<input type="text" name="message" placeholder="Type message here" />
<input type="submit" value="Send" name="s_say"/>
</form>
</div>
displayMessages() function in php:
function displayMessages() {
$user_id = getUserID();
$sql = mysql_query(strip_tags("SELECT * FROM inbox WHERE (send_id='".$user_id."' OR send_id='".$_GET['r']."') AND (rec_id='".$_GET['r']."' OR rec_id='".$user_id."') ORDER BY timestamp;"));
if (mysql_num_rows($sql) != 0) {
while($row = mysql_fetch_assoc($sql)) {
if ($row['send_id'] == $user_id) {
echo '<tr><td><p class="sm">'. $row['messages'] .'</p></td></tr>';
} else if ($row['send_id'] == $_GET['r']) {
echo '<tr><td><p class="rm">'. $row['messages'] .'</p></td></tr>';
} else {
echo "Unable to display messages.";
}
}
} else {
echo "Be the first to say hello!";
}
}
I would be highly thankful for any ones help as it's driving me a bit insane.
You've got a few things happening here that are going to cause you problems...
On the JavaScript side, setInterval is a hacky way to keep your content current, this could better be achieved with sockets. If you really want to do it this way, returning the whole document (including the HTML head) is not your best option -- maybe send an extra query param that tells your PHP to only send the messages section, or better yet, the messages that have been added since the timestamp you last checked.
In your markup, you can't put a paragraph tag directly inside your table, or raw text, as can come back from your PHP. You're not really using it as a table anyway, a list would probably be more semantic.

How can I pass the name of the field in form_error ()

It's part of my view. Me need transmit input name in on which i click.
Below is a script that will get the name input after click
<div class="form_hint"><?=form_error('this get value from javascript after click')?></div>
<?php echo form_open("onenews/" . $onenews['id'] . "#signup", $form_reg['main_form']); ?>
<?php echo form_input($form_reg['login'], $this->form_validation->set_value('login')) ?>
<?php echo form_input($form_reg['email'], $this->form_validation->set_value('email')) ?>
<?php echo form_input($form_reg['password']) ?>
<?php echo form_input($form_reg['conf_password']) ?>
<?= MY_Controller:: create_captcha(); ?>
<?php echo form_input($form_reg['captcha']) ?>
<?php echo form_input($form_reg['submit']) ?>
<?php echo form_close(); ?>
</div>
</div>
jq
<script type="text/javascript">
$(function(){
var curInput = '';
$('#form_reg').find('input').on('click', function(){
curInput = $(this).attr("name");
});
})
</script>
Or i must use ajax?
Thanks!
Your question is not clear at all, but I assume you want to dynamically change the content of the form_hint div. You can't do that with PHP. Once PHP renders the page, it shuts down and does nothing more. So the only way to make PHP show that message is after the form submit, but then you lose your click data. There is a way to save the clicked element in a session for example, but that would be a really bad solution.
So the best solution would probably be to list all the hints in a JavaScript variable, and call the appropriate one upon the click event, and fill the form_hint div with it.
$('.form_hint').text(yourAppropriateMessageHere);
An example with a hidden div for the login input field with exactly how you described would be:
<div class="form_text_login"><?=form_error('login')?></div>
JS
var loginMessage = $('.form_text_login').text();
// list others here
// then make a tree with switch/case or if/else
if (curInput == 'login') {
$('.form_hint').text(loginMessage);
}
else if (curInput == 'email') {
// do the same with the email message, etc.
}

JavaScript setTimeout function not executing as expected

I'm driving myself crazy here trying to figure out why this script is no longer executing as expected (it was working great yesterday, but I made a few minor changes and didn't back it up...now I can't figure out what the problem is).
<form method="POST" name="inventory_check" id="inventory_check">
<input type="text" name="stock_part" id="part_input">
<input type="hidden" name="site" value="2">
<input type="submit" value="Check Stock" id="submit">
</form>
<?php
if(isset($_POST['stock_part'])) {
$part = strtoupper($_GET['stock_part']);
$site = $_POST['site'];
$filename = 'system/inventory/'.$part.'.txt';
if(file_exists($filename)) {
$handle = fopen($filename, 'r');
$content = fread($handle, filesize($filename));
$content = trim($content, '&l0O(10U');
$content = trim($content, 'E');
fclose($handle);
date_default_timezone_set('UTC');
$mod_date = (filemtime($filename));
$current_date = time();
$subtract_date = ($current_date - $mod_date);
$subtract_date = ($subtract_date/3600);
if ($subtract_date <= 12) {
$stock = number_format($content);
echo '<script>document.inventory_check.style.display="visible";</script>';
echo '<div id="stock_results">There are '.$stock.' '.$part.' in stock.</div>';
}
else {
echo 'File too old.';
}
}
else {
echo '<iframe src="http://example.com/inventory_check.php?part='.$part.'&site='.$site.'" height="50" width="150"></iframe>';
echo '<script>document.inventory_check.style.display="none";</script>';
echo '<div align="center"><img src="http://www.aifittingsproto.com/images/load.gif"><br /><br />Searching</div>';
echo '<script>setTimeOut("recheck()", 2000);</script>';
}
}
?>
<script>
function recheck() {
document.inventory_check.stock_part.value="<?php echo $part ?>";
document.inventory_check.site.value="<?php echo $site ?>";
document.inventory_check.submit();
}
</script>
Basically this checks stock of a certain item on our internal servers (different domain than web server). What I'm trying to accomplish is the user keys in the part number...first it checks if the ftp-ed file exists on our server..if so, it checks the time it checks if its fresher than 12hrs, and then displays it if so. If not, it opens an iframe and sends the variables to our internal server for processing, which all works as expected. My issue is, I need to be able to have it recheck if the file exists after variables are passed through the iframe. I attempted to set this up by resending the variables and submitting the form every 2 seconds. Looking at the source, all the variables are populating as expected, etc. but it is not looping through and resubmitting the form. Any suggestions why this is failing, or a better approach? Thanks in advance.
You should try replacing setTimeout("window.reload()", 2000) with setTimeout("window.reload", 2000). My understanding is that you need to pass functions without the brackets for timeouts.

Categories