submitting a form through ajax for each ID - javascript

please guys, have some posts which i outputted from my database and now i want to make a comment form for each post and the form will be submitted through ajax method, but my problem is
the ajax method works for only the first outputted post and the form inserts into the database the mysqli_num_rows($query). ie if mysqli_num_rows($query) is =5, the form inserts into 5 rows in the database.
the remaining outputted forms reloads the page when the submit button is clicked.
This is what I want to achieve:
I want each form to be submitted without reloading.
I want the form to be inserted in only one row for each.
Here is my code:
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>

Change the input type="submit" to type="button" and make ajax on click of button.
For eg.:
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="button" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $("#my-form").serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
Above code will post the data without refreshing the page.

try this code
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form-"<?php echo $id; ?>>
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form-<?php echo $id; ?>').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>

Related

How to copy a file then rename it based on input field via buttonclick?

Good day experts!
I want to copy a file and rename it based on input value via button click. MY code is not working. There is no file being copied nor being renamed.
Here's my code:
<?php
error_reporting(0);
if($_POST['action'] == 'call_this') {
echo Success!;
};
$file = 'data.php';
$newfile = '$_GET['subject'].php';
echo copy($file, $newfile);
?>
<form action="<?php echo $newfile ?>" method="get">
<input type="text" name="subject" required>
<button type="submit">Change</button>
</form>
<script>
function change() {
$.ajax({
type: "POST",
url: 'data.php',
data:{action:'call_this'},
success:function(html) {
alert(html);
}
});
}
</script>
i think this is what you looking for:
<html>
<body>
<form method="post" action="copy.php">
<input type="text" placeholder="new name" name="newFileName"/>
<input type="submit" value="Change"/>
</form>
</body>
</html>
copy.php :
<?php
$file = 'sample.txt';
$newfile = $_POST["newFileName"].'.txt';
if (!copy($file, $newfile)) {
echo "failed to copy";
}else {
echo "copy with new name";
}
?>

Using Ajax to insert data but it's taking time to insert

i'm using ajax to insert data into mysql but if i press the submit button it's taking more time to insert data hopefully someone here can do better than me please give a feedback.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type ="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
My Ajax Code:
<script>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault();
var usId=$("#userId").val();
var mailId=$("#mailId").val();
var palId=$("#palId").val();
var mtext=$("#umText").val();
setInterval(function(){
$('#loadMesg').load("../validate/getMessage.php?mailId=<?php echo $_GET["mailId"]; ?>").fadeIn("slow");
}, 200);
$.ajax({
url:'../validate/updateMails.php',
method:'POST',
data:{
u_id:usId,
pal_id:palId,
u_mtext:mtext
},
success:function(data){
//alert(data);
$("#umText").val('');
$('#loadMesg').load("../validate/getMessage.php?mailId=<?php echo $_GET["mailId"]; ?>").fadeIn("slow");
}
});
});
});
</script>
And my Submit Form :
<form>
<input type="hidden" id="mailId" name="mailId" value="<?php echo $_GET["mailId"]; ?>">
<input type="hidden" id="palId" name="palId" value="<?php echo $_GET["palId"]; ?>">
<input type="hidden" id="userId" name="userId" value="<?php echo $_SESSION["u_id"]; ?>">
<textarea placeholder="Write M-Mail" id="umText" name="umText" class="input"></textarea>
<button type="submit" title="send" id="button"><i class="fa fa-paper-plane"></i></button>
</form>
https://code.jquery.com/jquery-latest.min.js
//link for JQuery latest version
Add only one JS:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>

javascript php AJAX refresh part of a DIV

I was trying to refresh the sidebar class "login" only when a user clicked on the button, however, I am not being able to access the login.php when the user makes the click. When I click on it it's doing nothing and it's refreshing the entire page too.
For what I could understand AJAX needs to be used to refresh only that DIV and the console.log is not being triggered. What I am doing wrong here?
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form action="" method="post">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#login_button").click("login.php", function() {
console.log("login_button clicked");
});
})
</script>
<?php
}
else {
echo '<p>User is logged in</p>';
echo '<form action="" method="post">';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#logout_button").click("logout.php", function() {
console.log("logout_button clicked");
});
})
</script>
<?php
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
</body>
Thanks in advance
Your page is refreshing because of action="" on your form tags.
Also you don't need method="POST" on form tag if you are using AJAX to do so. Just remove it!
You may efficiently use ajax request in your scenario.
A suggestion: you could separate your js code out of the PHP code.
so your code will look like this -
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form id="loginForm">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
} else {
echo '<p>User is logged in</p>';
echo '<form>';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
<script type="text/javascript">
$("#login_button").click(function () {
var data = $("#loginForm").serialize();
$.ajax({
type: "POST",
url: 'login.php',
data: data,
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("login_button clicked");
});
$("#logout_button").click(function () {
$.ajax({
type: "POST",
url: 'logout.php',
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("logout_button clicked");
});
</script>
</body>

copy text to textarea and submit all form in php

i have 20 user in my database and have 20 form in my site . this code show 20 form and i should send message every day to 20 user and want copy too all text area and submit them . i want have a form for send too all .
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
tihs code create 20 form with 20 id and :
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
Ok just i want 1 form too send too all , no more.

what does $('form#'+id) represent in the following js code?

In the following code, there is such javascript function sendPushNotification(id) in which there is such line var data = $('form#'+id).serialize() , what does $('form#'+id) mean? there is no form below that has the id "form#"+id ...
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
It selects a form element with an id of the value of the variable id. Assuming it is valid in that there are no duplicate IDs and id will never be the id of something not a form, it can also be written as simply $('#' + id).

Categories

Resources