I am building a Q/A website. When the user clicks on a particular question, he is redirected to the question page where the user can post answers.
Now, the issue is while the user clicks on "Answer" link, few things are processing in the background like updating db, sending mail, etc. I am trying to display a load indicator in the UI but the AJAX function is not getting triggered.
Here is my code:
HTML:
<span id="msg"><img src="ajax-loader.gif"/></span>
<a id="sub-link" href="javascript:void(0)" onclick="loadAnswerList(document.getElementById('user-ans').value,<?php echo $qid; ?>,'<?php echo $posted_by; ?>')">Answer</a>
JS:
$(document).ajaxStart(function () {
$('#msg').show();
}).ajaxStop(function () {
$('#msg').hide();
});
AJAX request
function loadAnswerList(ans,qid,postedBy,page) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ans_container").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page,true);
xmlhttp.send();
}
I also tried adding $(document).ready(function() { .... }); above the ajax but still it is not working. Am I missing anything?
Am using jQuery version 3.2.1
jQuery does not work with the native XMLHttpRequest object. The ajaxStart and ajaxEnd lines you are using deals with their api. So in order to use it, you need to use jQuery's .ajax() or .get() methods.
Thanks for the details.
This is the modified function:
function loadAnswerList(ans,qid,postedBy,page) {
var answer=ans;
var qstnid=qid;
var postby=postedBy;
var pg=page;
var request = $.ajax({
type: "GET",
url: "load_answers.php?ans="+ans+"&qid="+qid+"&postedBy="+postedBy+"&page="+page",
data: {ans: answer, qid: qstn_id, postedBy: postby, page: pg},
dataType: "html"
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Please correct me if am wrong. One more thing - I want to display the response from the php page to a particular div as I have done in my previous ajax request.
document.getElementById("ans_container").innerHTML = this.responseText;
How do I do it here?
Related
I want to autoupdate page using PHP and Ajax. Right now I have this code on a page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<i class="fa fa-heart-o"></i>
</body>
</html>
When the user clicks on the link it is redirected to another page called "Page-Like.php"
include("config.php");
//get vars
$idSubliminal=$_GET["idSubliminal"];
$idCategoria=$_GET["idCategoria"];
// mysql_query("insert into Rating .... (mysql insert query)
echo "<script>
location.href=\"AudioSubliminal.php?idSubliminal=$idSubliminal&idCategoria=$idCategoria\";
</script>";
What I want is to do this usig Ajax in order to not refresh the page. I know I'm missing the javascript code, but I would like to get some suggestions to complete this script.
Thanks!
All you need is a basic ajax request to achieve your functionality. check the sample request below.
function ajaxpr(){
var URLString="idSub=12&idCat=32";
ajax_request = $.ajax({
type: 'GET',
url: "Page-Like.php",
data: URLString,
dataType : 'html',
context: $(this),
success: function (msg)
{
//perform the required operation after success
});
}
add function onclick on tag . then define that function using :
$.ajax({
type: 'GET',
data: {idSub: "12", idCat: "32"},
url: "Page-Like.php",
dataType: 'JSON',
success: function (response, textStatus, jqXHR) {
//DEFINE FUNCTION HERE
}
});
This is using ajax function without refresh page.
You can use many methods to implement Ajax on you're code.
One of this is jQuery, other is mootools, etc.. Depends of wich library you know or want to learn.
Using ajax to load a page is easy. Follow this link http://www.w3schools.com/ajax/
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "Page-Like.php?idSub=12&idCat=32", true);
xhttp.send();
}
Now it's just a matter of putting event listener to run loadDoc() function. If the link is dynamic, you can parse the parameter to the function.
However, I notice you have a js script inside your php which will redirect again to AudioSubliminal.php. If this is your desired flow then it's okay. If not, you can create another function
function loadAudioSubliminal(idSub, idCat) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "AudioSubliminal.php?idSubliminal=" + idSub + "&idCategoria=" + idCat, true);
xhttp.send();
}
and modified loadDoc() to receive a parameter such that idSub and idCat can be passed again. for Example :
function loadDoc(idSub, idCat) {
var xhttp = new XMLHttpRequest();
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
// run the function after finished loading Page-like.php
loadAudioSubliminal(idSub, idCat)
}
xhttp.open("GET", "Page-Like.php?idSub=" + idSub + "&idCat=" + idCat, true);
xhttp.send();
}
I am new to AJAX and presently learning it from Head First AJAX. The problem I am facing is really weird. I developed a simple program that creates a request through JavaScript and then shows the output.
main.js
window.onload = initPage;
function initPage() {
request = createRequest();
if(request == null) {
alert("request could not be created");
}
else {
var url = "requestMe.php";
request.onreadystatechange = showResult;
request.open("GET", url, true);
request.send(null);
}
}
function showResult() {
if(request.readyState == 4) {
if(request.status == 200) {
if(request.responseText == "okay") {
alert("A successful request was returned");
}
else {
alert("ALERT : " + request.responseText);
}
}
else {
alert("Request status received was not correct");
}
}
}
//--function to create request objects--
function createRequest(){
try{
request = new XMLHttpRequest();
}
catch(tryMS){
try{
request = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(otherMS){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(failed){
request = null;
}
}
}
return request;
}
Now, here is the php script.
requestMe.php
<?php
echo 'okay';
?>
This code should give the alert A successful request was returned
But instead it gives the result ALERT : okay
The weird thing is this same code was working yesterday for me when I tried it and now it is giving me this result. I tried to create similar programs and they all are showing me this kind of weird behavior. The responseText received is correct because it appends okay after ALERT :. What wrong am I doing here in the code? Why is it going to the else part when the responseText received is correct?
Any Help? Thanks in advance.
I personally would do it using jQuery's Ajax Function in the following way:
document.addEventListener("DOMContentLoaded", function()
{
$.ajax({
"url": "requestMe.php"
}).done(function(data)
{
if(data == "okay")
{
alert("A successful request was returned");
} else
{
alert("ALERT : " + data);
}
}).fail(function()
{
alert("Connection Failed");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I haven't tested this Script, but it should in theory work out well.
Do one thing add exit; after echo 'okay';
Issue in your code is after ?> there is extra space available you can fix it either by removing ?> or removing extra space after ?>.
I hope it will fix your issue.
I'm having a bit of trouble understanding how to get this to work. I'm loading a page with data from mysql db table using jquery. I'd like to be able to do mysql updates on individual records without refresh. Here's the code I've tried, but can't get the update to work.
index.php
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","data_ajax.php?q="+str,true);
xmlhttp.send();
}
}
Here I have a drop-down in a while loop to retrieve the desired records and post it into a <div id="txtHint"></div>. So far, so good.
Now, I'm putting the following in data_ajax.php to do the mysql update.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".update_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "update_ajax.php",
data: dataString,
cache: false,
});
return false;
});
});
</script>
Where I have a text link <a href='#' id='".$row['id']."' class='update_button'>".$label."</a> that should call the action above to do the update. All this does it jumps the page to the top and nothing happens. The update_ajax.php doesn't seem to get called when link is clicked. I know it's something simple I'm missing. Any help would be appreciated.
What I would suggest is including jQuery directly in index.php, which would then allow you to use event delegation to handle most of the work.
With jQuery being included in index.php, you can use jQuery to do the showUser ajax request too.
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "update_ajax.php",
data: dataString
});
return false;
});
});
Update your version of jQuery. Your example shows you using version 1.4.2.
The $.ajax shorthand code was introduced after version 1.5.
How can I refresh a particular part of a web page with a time interval (not entire page)?
You can use Ajax for your purpose.
suppose you want to check username availability before registering a user to your site.
create a request object asynchronously
function createRequest()
{
try{
request=new XMLHttpRequest();
} catch(tryMS){
try{
request=new ActiveXObject("Msxml2.XMLHTTP");
} catch(otherMS){
try{
request=new ActiveXObject("Microsoft.XMLHTTP");
} catch(failed) {
request=null;
}
}
}
return request;
}
Next is the code to send a asynchronous request
function checkAvailability (username) {
request=createRequest();
if(request==null){
alert("Ajax request not possible on your browser");
return;
}
var url="checkAvailability?username="+username;
request.open("GET", url, true);
request.onreadystatechange = showStatus;
request.send(null);
}
Track the response
function showStatus () {
if(request.readyState == 4) {
if(request.status == 200) {
var response = request.responseText;
if(response == 1){
//username available
} else{
//username not available
}
}
}
}
Suppose you have a DIV in your your Web Page that you want to refresh :
<div id="myDiv"> </div>
To refresh it using javascript you just have to select it and change the html code :
document.getElementById("myDiv").innerHtml = "Your new html code to display"
If you want to deal with forms, database queries ...
You have to use AJAX to call some php scripts for example without reloading the current page ...
You are talking about AJAX
Look at http://api.jquery.com/jQuery.ajax/ for jQuery
But please consider learning the underlying javascript language - you will be better for it in the long run
here is a simple example
http://www.degraeve.com/reference/simple-ajax-example.php
The history behind ajax can be found here http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications
I have a working PHP web service that returns data (if I input the url into the browser I get the results). I need to use Javascript to retrieve this data from my web service, but I'm not too great with Javascript. Based on all the tutorials, examples, and StackOverflow questions and answers I've read this should work, but it doesn't. Please Help!
<script type="text/javascript">
var url = '*working url*';
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
else { document.write('Perhaps your browser does not support xmlhttprequests?'); }
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myObj = eval ( xmlhttp.responseText );
} else {
// wait for the call to complete
}
};
</script>
Also, I need help making sure that I'm calling this correctly. Currently I do it like this, which may be the problem:
<script type="text/javascript">
document.write(myObj);
</script>
I'm aware this doesn't directly answer your question but if you are "not too great" with javascript I would recommend just going straight to jQuery instead of messing with the lower level objects.
It will also help you with cross browser compatibility.
http://jquery.com/
http://api.jquery.com/category/ajax/
However if you have a particularly boring day some time in the future, going back and learning what's going on behind the scenes is always beneficial.
This would be a simple ajax post using jQuery (with a text response):
$.post(
"test.php",
{ postValue1: "hello",
postValue2: "world!" },
function(data){
alert("Success: " + data);
},
"text");
To answer your second question (in comments), the code looks correct but perhaps you're getting a bad response. You can attach additions events onto the ajax call to get additional information.
This code is borrowed and modified from jQuery's site:
http://api.jquery.com/jQuery.post/
I got the function parameter info from:
http://api.jquery.com/jQuery.ajax/
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("example.php", function() {
alert("success");
})
.success(function(data, textStatus, jqXHR) { alert("second success"); })
.error(function(jqXHR, textStatus, errorThrown) { alert("error"); })
.complete(function(jqXHR, textStatus) { alert("complete"); });