Using ajax to refresh a div content - javascript

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).

Related

after ajax success refresh / reload page but prevent page blink

as title you see, I meet some problem with my website,
I use ajax to read my API, and after ajax success, I need to reload page to display some data,
Unfortunately, the page sometime will blink and then reload, but sometime will not.
And I use setTimeout to achieve that, because I'm writing shopping cart page,
It allow user edit their shopping carts' goods.
My idea is: after user stop click plus or minus button or stop typing quantity about 1 second,
ajax will execute to read my API, after ajax success, reload page.
So, is there have any ways to prevent page blink?
Or maybe I can made a loading gif to display on the page?
My code will be like:
var timeout = null;
$('.num').on('keyup', function() {
var newNum = $(this).val();
var pid = $(this).attr("name");
clearTimeout(timeout);
timeout = setTimeout(function() {
if(newNum <= 0){
alert("At least 1 product!");
$(this).val("1");
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: 1
},
dataType: "json",
success:function(data){
window.location.reload(true);
},
});
}else {
$.ajax({
type: "post",
url: myAPI,
async: false,
data: {
pid: pid,
newNum: newNum
},
dataType:"json",
success:function(data){
window.location.reload(true);
},
});
}
}, 1000)
});
You can add a loader gif as you want then remove when document loaded.
<div class="loader-fix" style="position:fixed;height:100vh;width:100vw;background:#ffffff;">
<img src="your.gif" />
</div>
<script>
$(window).on('load', function (e) {
$('.loader-fix').fadeOut('slow', function () {
$(this).remove();
});
});
</script>
What is the point in using ajax when you want to reload the page to show updated data...?
success:function(data){
window.location.reload(true);
}
What is the use of above piece of code..?
For your purpose a simple form submission thing was enough, but you have used ajax getting data but not using it anywhere.
If you want to reload the page, then better go with solution by Şahin Ersever.
If you want a dynamic site, where data is fetched from backend in background and updated on frontend without refreshing the page, do something like this.
<html>
<body>
<h1> Dynamic load using AJAX </h1>
<div class="dynamic_div">
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
</div>
<button onclick="letsload()">Load</button>
<script>
function letsload(){
$.post("someurl",{ data1: "value1", data2 : "value2"},
function(data, status){
if(status == "success"){
$('.dynamic_div').html(data);//Loading updated data
}
});
}
</script>
</body>
</html>
On data variable, you can echo out desired html/json or a success/error code, and handle the data/code in ajax function accordingly.
Edit :-
Looking at your comment But I check my website, if ajax success, I use console.log to print my data, it's not working, but if reload page, it can work.
I have a quick and easy solution for this.
Let's take above example, which I have given.
Suppose if I want updated data to be displayed in dynamic_div what I will do, is I keep the element to be shown inside that div in separate file.
eg:- updated.php
<div class="some_class">
<!-- here some more elements may/may not contain dynamic data or some server side based-->
<!-- Like this -->
<h1> Name:- <?php echo $name;?> </h1>
<p> <?php echo $some_other_variable;?> </p>
<p> <?php echo $some_other_variable;?> </p>
....
</div>
Now What I do is on success of my ajax, I will load this div in to my .dynamic_div like this.
success:function(data){
$('.dynamic_div').load("updated.php");//Load the inside elements into div
}
Now you will get updated data, as you have already updated it somewhere in backend, so load() will load a page inside a division, without refreshing the whole page.
Comment down for any queries.
AJAX Read data from a web server - after a web page has loaded
Update a web page without reloading the page
Send data to a web server in the background
What is Ajax
If you want to reload page then don't use ajax call,
but if you want to load data using ajax then update your html using JavaScript in ajax success message.

How would you design this webpage with multiple forms?

I currently have a simple php/html page with only one form, where the user inputs a number, then the page loads itself (but this time with parameters).
Some key codelines :
<form action="index.php" method="get">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if (!isset ($_GET["name"])) {
echo "<div> Adding some content related to the input </div>";
}
?>
Now i'm looking forward adding 3 more fields, and split my page for each form.
The user should be free to use the 4 forms separately, I don't want to have the page reload every time. I'm unsure how to design this page - should i rework my page and work with JS ?
I have basic knowledge with PHP, a little with JS. I will be able to google up most things i need but first i need a proper direction :) thanks !
you can use AJAX for this purpose...
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
AJAX is a must if you don't want the page to reload between each interaction.
If you have trouble with it and want to opt for just PHP (with page reloads) you can handle multiple forms on one page easily enough - my preferred method is to set a hidden value in the form called 'action' settings its value & reading this in again when the page loads for example:
<?php if(isset($_POST['action']))
{
$action = $_POST['action'];
switch ($action)
{
case 'hello':
echo 'hello';
break;
case 'bye':
echo 'bye';
break;
}
}
?>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="hello"/>
<input type="submit" value="hello"/>
</form>
<form method="post" action="Untitled-5.php">
<input type="hidden" name="action" value="bye"/>
<input type="submit" value="bye"/>
</form>
You could then save and echo out the values for each form each time keeping them updated as the user interacts with each of the forms.
AJAX is the nicer solution however
If you do not want to reload the page every time you submit each form then you should use Ajax for calling your api. You write the separate api in PHP, and then call that api in Jquery's Ajax.
Here the page won't be reloaded. Also you can call the ajax on each of the button click.

How to handle php loop through elements with jquery

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

Javascript form submit preventDefault not working when form is retrieved with AJAX

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

Pass variables from HTML form -> ajax load()

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.

Categories

Resources