I have created a page "index.php" with a lot of divs and I need to refresh only one of the divs when the form is submitted.
This div loads the content from chat_window.php which is as follows:
<div id="chatbox">
<?php echo $res; ?>
</div>
<!-- Chat user input form-->
<?php echo $formchat; ?>
chat_window.php uses dynamic content - $res and $formchat from chat.php.
Everytime I post the form the content of $res and $formchat is modified and I need to reflect the same in my page which loads chat_window.php.
I used AJAX and jQuery to do the same as follows:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("input#chat").val();
var dataString = "chat="+ name;
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
}
});
$("#chatwrapper").load(chat_window.php);
return false;
});
});
The index.php has a div to show the chat_window as follows:
<!-- Chat window-->
<div id="chatwrapper">
<?php include ("chat_window.php"); ?>
</div>
As per my analysis, when I post the form, $res and $formchat are getting updated in the php. But when I load the chat_window.php, it doesnot loads the modified values. It rather loads the initial static values.
(Please dont suggest setInterval() as I dont want to refresh the page automatically).
Javascript is non-blocking, so it means that the interpreter does not wait for jobs to complete before processing the next one.
In your code, $("#chatwrapper").load('chat_window.php'); is being called pretty much before the ajax request above it completes. You will need to use the ajax success event to call the reload.
Try:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load('chat_window.php');
}
});
Try moving the .load() statement into the ajax success handler:
$.ajax({
type: "POST",
url: "programo/bot/chat.php",
data: dataString,
success: function() {
$("#chatwrapper").load("chat_window.php");
}
});
The $.ajax() call is asynchronous, which means that execution does not pause waiting for the response, rather, it moves on directly to the .load() call. (Which is also asynchronous, so really you've no guarantee about the order the response from each call will come in unless you don't make the second call until the first one finishes.)
I got my work done. Though I used another way of doing it.
What I have understood after few days of R&D is that, when we submit the form to a php, the request is sent with input params. When your php file processes this request, it might be updating some global variables. It completes processing the request and returns the control back to the calling index.php page.
The important thing to notice is:
The variable updates made while processing the form submit request do not persist after the control is returned. The global php variables will only get updated when the page gets refreshed.
So, if there is a strict requirement to avoid page refresh, collect the processed data from the php in some output string and pass it back to index.php like this:
$responseString = $res . "|" . $formchat;
echo $responseString;
The success parameter of .ajax will receive this output and accordingly you can update your chat window or any other form.
Related
I already checked around for this answer but all are different problems just same title (to prevent random duplicate marks).
Here is an ajax call to the click of the filter button that should send the data inserted in the form formmatcat to the php file formfilt.php and should load the result in a div with id resultins
<script>
$(function () {
$('#filter').on('click', function(event){
event.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize(),
success: function () {
$("#resultins").load('formfilt.php');
}
});
});
});
</script>
I set the preventdefault to load only in the div without redirecting to the php file and this works but if I put the preventDefault it echoes the string I build by concatenating values sent from the form with those empty values. The strange thing is that if I remove preventDefault of course it redirects and loads the php file but with the correct values:
Moral of the story, data in the form with the ajax call goes correctly to the php file but looks like preventDefault don't let this. Thanks in advance
Here's the structure of the html part with the form
<form id="formmatcat" method="post" action="formfilt.php">
.
.
various textboxes
.
.
</form>
What you're doing is sending an AJAX request toformfilt.php, when this call happens and it returns a response it will be stored as a parameter within the success or $.done function as I'll mention later, that is where your echo'd content will be.
What you're doing here is when the call is successful, you simple send a GET request to the same page. Since that GET request differs from the AJAX POST request and has no POST parameters you'll not get the correct output.
By simply submitting the form and letting it go to the page rather than cancelling the request you're getting the right values as you're directly posting to the page with the correct values, when you call the load function you're doing a seperate AJAX get request.
What load actually is, is a rough equivelant to $.get which is shorthand for $.ajax.
Looking at jQuery AJAX docs
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
Basically, a $.ajax() call returns a promise object that you can chain callbacks on when it is finished. Also note that data here will be the actual content within your PHP file, thus if you rewrite your AJAX call like so:
<script type="text/javascript">
$(function() {
$('#filter').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'formfilt.php',
data: $('#formmatcat').serialize()
}).done(function(data) {
$('#resultins').html(data);
});
});
});
</script>
It will then continue to load the output of formfilt.php into the div with ID resultins.
dont use form, use input without form, and use button tag use onclick to run function, if you use form, it will submit and redirect,
i'm not good with ajax on jQuery
but if i were to use javascript/XHR
var CB=document.getElementById("filter").value; //get input/filter value
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200)
document.getElementById('contain').innerHTML=xhttp.responseText;
};
var url="formfilt.php?filter="+CB;
xhttp.open("GET", url, true);
xhttp.send();
if you want to use post :
xhttp.open("POST", "formfilt.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('filter='+CB);
sorry, i'm also learning, and new to this, just learning a week ago,
I've recently changed my searching page to a searchable datatable page due to my employer's request for easier data management. The problem is that it is taking too long to load.
I'm wondering it there is a way to only load like a portion of the table and finish loading the page first. Then finish off loading the rest of the table after that, e.g. while the user actually attempt to search for the data.
This was requested because the user might want to navigate to other parts of the page instead of using the datatable.
Extra info : The page is in .php and the data is loaded using php do-while loop. Maybe we can do a workaround using php functions?
Using the AJAX method recommended in the comments, the following is similar to how you could handle the page-load. You would need the jQuery library for the below.
Initial page
<script type="text/javascript">
// when the page is done loading,
// let's send a call to load more data
$(document).ready(function(){
myFunction();
});
// function to handle AJAX request to gather data
function myFunction(){
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
success: function(data){
// handle the data using the "data" variable
}
});
}
</script>
AJAX Page
<?php
if(isset($_GET["loadData"])){
// call query here and echo information
}
It may be recommended, to actually use a PHP function called json_encode() to echo back the information from your AJAX page in JSON form. This would allow you to transmit an array of information, instead of raw data. You would then need to update your AJAX request function similar to below.
$.ajax({
type: "POST",
url: "./linkToMyPHP.php?loadData=1",
dataType: "json",
success: function(data){
$("#myDivToChange").html(data);
}
});
You can read up on JSON at this highly rated question.
I am trying to get a div to reload once a checkbox has been selected or unselected and the form has been submitted. I have used AJAX and can get the form to submit on change, which works no problem. However the page has to reload to display new data.
I have built the php in such a way that it doesn't need to refresh the page or fetch a new page. If the div and it's content refreshes that should be sufficient to display the new filtered data.
Below is what I have written so far
$(document).ready(function() {
$("input:checkbox").change( function() {
$.ajax({
type: "POST",
url: "index.php?action=resortFilter",
data: $("#locationFilter").serialize(),
success: function(data) {
$('.resorts').html(data);
}
});
})
});
What do I need to do to get the div to reload after the request has been made?
I use class methods to handle the processing which return only the array of data. The requests are made to the class from a php function.
What I'm trying to do isn't actually possible to because PHP is a server side language. The best bet is to create a new intermediate file that can handle the display of the data so that it can be brought in through a normal AJAX request and get the new display from it
Where is the Ajax request? You are submitting your form through HTML/Browser. You need to use the following code:
$(document).ready(function() {
$("input:checkbox").change( function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#locationFilter").serialize(), // serializes the form's elements.
success: function(data)
{
$('.resorts').html(data);
}
});
})
});
Source: jQuery AJAX submit form
this sample loading code maybe help you
<div id="loadhere"></div>
$('div#loadhere').load('ajaxdata.php',{datatosend:whatyouwantforexamplehelloworld});
So I have a simple web-app interface that is relying on AJAX to build and control which settings a user can see at any one point in time. Think of them as acting like sub-menus.
<script type="text/javascript">
$(document).ready(function(e) {
$(".option").click(function() {
var method = $(this).attr("id");
var target = "";
switch(method){
case "optManPpl":
target = "/controls/location/manage_people.php";
break;
case "optManLoc":
target = "/controls/location/manage_locations.php"
break;
}
$.ajax({
type: "POST",
data: "user=0",
url: target,
success: function(msg){
$("#controls").html(msg);
}
});
});
});
</script>
<div id="options">
<div id="optManPpl" class="option"> Manage People </div>
<div id="optManLoc" class="option"> Manage Locations </div>
</div>
<div id="controls">
</div>
This page is obviously called and displayed from another ajax call and loaded to the screen. When I click on "optManPpl" or "optManLoc" for the first time, the call goes through great and returns the expected result. However, the second time I click on either of them (2 calls in any combination), the entire page is returned instead of the [target] url.
EDIT: I am "chaining" AJAX calls throughout the application. I am relatively new to working with AJAX in a web-app situation, so I'm not sure if this is the best way, but it is the way I came up with for getting user input from the forms into PHP without having to resubmit the page.
EDIT: the attached image is what the page looks like after the second call. After the FIRST call, the "controls" div tag is instead populated with 4 other div tags.
please put exit after last line in manage_locations.php file.
also you can check out put by following.
$.ajax({
type: "POST",
data: "user=0",
url: target,
success: function(msg){
alert(msg); return false;
$("#controls").html(msg);
}
});
Here you ll see the particular output only. so that you can find the results in an alert.
I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.