I have an HTML form that will return as HTML format with JQuery Ajax after the insertion query is successful.
comment.php
$post_id=$_POST['id'];
mysql_query("INSERT INTO comment(comment,post_id,)VALUES('$comment','$post_id')");
if(!mysql_errno()){
?>
<p><?php echo $comment; ?></p>
This is my JQuery code that will send the request and values and return the HTML form after the insertion query succeeds.
index.php
// on post comment click
$('.bt-add-com').click(function(){
var theCom=$(this).siblings('.the-new-com');
if(!theCom.val()){
alert('You need to write a comment!');
}else{
var post_id=$(this).parents(".post_id").attr("id");
$.ajax({
type: "POST",
url: "comment.php",
data: "act=add-com&comment="+theCom.val()+"&id="+post_id,
success: function(html){
theCom.val('');
$('.the-new-com').hide('fast', function(){
$('.new-comment-line').show('fast');
$('.new-comment-line').after(html);
});
}
});
}
});
This my form. It's running within a loop of posts submitted by the user every time.
<form action="" method="POST" class="post_id" id="<?php echo $post_id; ?>">
<span>Write a comment ...</span>
</div>
<div class="new-comment-line"></div><----here is a line before the comment initiates..--->
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
</form>
And now my question is that my all code works very well except last few lines of JQuery code.
$('.new-comment-line').after(html);
The line of code when my form returns the HTML form from comment.php after the Ajax request has the problem. The form prints every time, in every post, that the user submitted the status.
How should I handle the form? I want my comments to print every time only in the specific post submitted by the user.
Obviously $('.new-comment-line') is a class selector and you are selecting all elements in this class. As you start your function by clicking on a button, I suggest the selection of correct element relative to the clicked button. So immediately after clicking a button, select the correct element:
var correctElement=$(this).siblings('.new-comment-line');
and then add the html to it when needed:
correctElement.after(html);
Related
I want to fetch some data (without reloading page) based on UserIds that are linked to a tags. I am not able to pass on UserID to jquery successfully and accurately. What it does is, just picks the last UserID and fetches it.
I have also tried to pass on variable throuh a-tag URL but could not get it accurately in jquery file. It fetches the data from already opened url, not the one being clicked right now.
HTML:
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<input type="hidden" id="ANP" value="<?php echo ($Messagers1['UserID']*3);?>"></input>
<a class="LoadMsgsBtn">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
jquery:
$(document).ready(function(){
$(".LoadMsgsBtn").click(function LoadMsgsfunc(){
var ANP = $("input#ANP").val();
var Msg=6;
alert(ANP);
$("#result").load("LoadDB.php",{
ANP: ANP,
Msg: Msg
});
})
});
LoadDB.php:
<?php
$ID = $_POST['ANP'];
$Msg = $_POST['Msg'];
echo $ID . "\n";
echo $Msg;
I want to fetch data from database without reloading using UserID sent. $Messager is an array having multiple rows, there is a series of a-tags. clicking on any a-tag sents corresponding UserID to jquery code
Classic issue of multiple element selection. It's a bit tricky when you are using loops and jquery selectors ;) Check out the following code. It should work like butter B)
<?php foreach($Messagers as $Messagers1){ ?>
<form action="" method="post">
<a class="LoadMsgsBtn" href="javascript:void(0)" onclick="featchData('<?php echo ($Messagers1['UserID']*3);?>')">
Click to load data
</a>
</form>
<?php}?>
<div id="result">
<--The output will come here!-->
</div>
Javascript
function featchData(userId)
{
console.log(userId);
//if you get the id, write in the rest of the code here ;)
}
I have a form, which I submit with Javascript and preventDefault. Everything works fine. However, when I retrieve the form with an AJAX call together with other data from a DB, the form will not submit with Javascript anymore, but tries to refresh the entire page with the normal action="" and method="post". It seems that due to the AJAX call, the preventDefault is somehow disabled?
AJAX Call to get form and other data from DB:
Load Names
<div id="form-container"></div>
<!-- is empty, but contains the form upon ajax call above-->
The AJAX retrieved HTML Form to submit with Javascript:
<div id="form-container">
<!--let user add a name to DB not contained in DB list below-->
<form method="post" action="" id="addnameform">
<input name="name" id="name" type="text" value=""/>
<input type="submit" name="add-name-submit" value="Add"/>
</form>
<!--get a list of names from DB-->
<?php
$sql = "SELECT * FROM names ORDER BY name ASC";
$query = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($query)) {
$name = $row["name"];
echo ...
} // end while
?>
</div><!--end-container-->
Javascript to submit HTML form above:
$("#addnameform").submit(function(event) {
event.preventDefault();
var $form = $("#addnameform");
var name = $form.find( "input[name='name']" ).val();
$.ajax({
url: "ajax.php",
type: "POST",
...
As said, everything works perfectly when the form is displayed on the page upon page load. But as soon as I wrap it inside a container, which at first is "empty", but shows up upon an AJAX call, the preventDefault is somehow disabled.
You have to bind the submit event to your body (or any other parent DOM which exists from begining)
$("body").on('submit', '#addnameform', function(event) {
//...
});
You need to have a parent dom object which you load async your form, can you try your jQuery code like below;
$(function(){
$("#form-container").append("<form id=\"addnameform\" method=\"post\"><button type=\"submit\">Submit Me</button></form>");
$("#form-container").on("submit","#addnameform",function(event){
event.preventDefault();
alert("Submit fired!");
//Your business goes here...
return false;
});
});
Here is a working example: https://jsfiddle.net/1fta504n/2/
PS: #form-container can be any kind of dom element ex document, "body", "div", ".class" etc
Hope this helps
I'm using JavaScript to handle my form submission and an Ajax call to refresh a certain div only "not the entire page", the form submission is successful but the value inside of the div doesn't refresh. I've tried other methods/solutions on stack overflow but they all seem to load the entire page or the content of the div is hidden on form submission.
ajax.js
$(document).ready(function () {
$('.ajaxform').submit(function (e) {
e.preventDefault(); // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType: 'html',
url: "info.php", // the file to call
cache: false,
success: function (response) { // on success..
$(".ld").load("info.php .ld"); //this hides the content of the div
// $('.ld').html(response);----This loads the entire page inside the div
}
});
return false; // cancel original event to prevent form submitting
});
});
info.php
<html>
<head>
</head>
<body>
<?php
...................
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" id="ajaxform" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
echo '<div id="emailform"></div>';
}
?>
</body>
</html>
i am trying to refresh the variable "$likes" inside the div tag, without refreshing the whole page, right now my current code hides the variable on form submit. i have to refresh manually to view any changes to "$likes".
You are sending an XMLHTTPRequest to a whole document and not to a portion of PHP (It is the latter that you need as I understand from your question). Additionnaly, you are sending the request to the same current page info.php, it is better to separate the concerns by splitting your PHP code to two parts (the one the renders the intial form and the one that is intentended to process it server side).
As a result, the AJAX will return all result of info.php (static markup + generated markup) and return all the final HTML and load it in .ld.
What I suggest is to create two files: form.php and process-form.php.Your AJAX call will be performed when document returened by form.php is ready and will be sent to process-form which will return required data after form processed.
And this should work without refreshing the page (the main purpose of using AJAX).
Hello everyone I'm working on a project and I'm pretty sure I've made a rather large mistake. Basically I have some PHP code that retrieves some values from a database, and each row gets its own in a table. Then each one has a button that deletes it, which shows a small dropdown form asking for some details along with a submit button. However, I for some reason wasn't thinking that there would be multiple forms, and have each input an id, resulting in multiple elements having the same id.
So, in JavaScript, an AJAX request is made when a user submits deleting a row, and the values from the form (values are found by the ID of the input) are sent as POST variables to a PHP script. Since I'm doing this, the AJAX request only works if they're deleting the first row, but not any under that.
So, this HTML is output by PHP to add a dropdown form to each row:
<td class='dropdown'><a class='dropdown-toggle' href='#' data-toggle='dropdown'><button class='btn btn-warning'>Kick</button></a>
<div class='dropdown-menu' style='padding:15px; width:340px'>
<div class='form-group'>
<form id='delete-form'>
<label for='delete-reason'>Reason: </label>
<input class='form-control' id='delete-reason' name='delete-reason'>
<input type='hidden' id='delete-id' name='delete-id' value='". $value['Name'] ."''>
</div>
<br>
<input type='submit' id='delete-submit' name='delete-submit' value='Delete ". $value['Name'] ."' class='btn btn-default'>
</form>
</div>
</div>
Then I use this JavaScript to submit the form to send the data from the form to a PHP script by an AJAX request.
$("#delete-form").submit(function(e){
e.preventDefault() // stop form from submitting
var reason = $("#delete-reason").val();
var id = $("#delete-id").val()
$.ajax({
type: 'POST',
url: 'php/ajax.php',
data: {
deletereason: player,
deleteid: id
},
success: function(response){
$("#delete-result").append(response);
$("#delete-result").fadeIn(500);
}
})
})
So, like I said, it only works on the first row because on the others, it just gets the values of the first found input with that id. And when I do it on any row besides the first, it adds the values as a query string, which doesn't do anything because well, it's not supposed to.
However I don't really know how to make it where it would get the values from the current form, not the others, and that's why I'm here.
I understand this is all pretty confusing and if you need me to clarify anything or explain more I'd be happy to.
Any suggestions?
You need to have unique id for each form and input element and then follow the answer provided by #ArunPJohny. But if you cannot have unique id for each element then follow below code
$(".form-group form").submit(function (e) {
e.preventDefault() // stop form from submitting
var reason = $(this).find("input[name='delete-reason']").val();
var id = $(this).find("input[name='delete-id']").val();
$.ajax({
type: 'POST',
url: 'php/ajax.php',
data: {
deletereason: player,
deleteid: id
},
success: function (response) {
$("#delete-result").append(response);
$("#delete-result").fadeIn(500);
}
});
});
What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.