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.
Related
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?
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 integrating my site ajax to load content without reloading the page. Everything works fine but are of this style url http: // mysite / #.
I wish that were generated url to reload the page to remain in the same place, I could use also have a new URL for the likes of facebook. Any idea what could be wrong? I leave the code:
function nuevoAjax() {
var xmlhttp = false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function Cargar(url) {
var center = document.getElementById('center');
ajax = nuevoAjax();
ajax.open("GET", url, true);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
center.innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
And the button:
<img src="<?php $_SERVER['DOCUMENT_ROOT']?>/image/road.jpg" width="60" height="34"/>
This is the div that loads dynamic content
<div class="center"></div>
New EDIT:
<sript src:"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$("#loadContent").on("click",function(event){
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
type: 'GET',
data: {"anydata":"anydatavalue"},
success : function(reponse){
$("#center").html(reponse);
}
});
});
</script>
The button:
<li>BIO</li>
This is a code to do the task that you want in jquery ajax
include jquery file in the head of your page like this
<sript src:"https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script
assign a id to your anchor tag
<img src="<?php $_SERVER['DOCUMENT_ROOT']?>/image/road.jpg" id="loadContent" width="60" height="34"/>
Jquery Ajax bind with click event
<script>
$("#loadContent").on("click",function(event){
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
type: 'GET',
data: {"anydata":"anydatavalue"},
success : function(reponse){
$("#center").html(reponse);
}
});
});
</script>
I have an AJAX script powered by PHP backend which parses/gathers data from an XML file. I am trying to eliminate the PHP script and replace it with a JavaScript solution with jQuery. Here is my current JS script which is binded with a PHP script:
function showUser(str) {
if (str == "") {
document.getElementById("loadMe").innerHTML = "";
return;
}
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("loadMe").innerHTML = xmlhttp.responseText;
}
}
//xmlhttp.open("GET","lib/getuser.php?q="+str,true);
//xmlhttp.send();
};
Here is the PHP script (getuser.php)
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("../Administration/data/people.xml");
$x=$xmlDoc->getElementsByTagName('fullName');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}
$user =($y->childNodes);
for ($i=0;$i<$user->length;$i++)
{
//Process only element nodes
if ($user->item($i)->nodeType==1)
{
if($i != 1 && $i != 0) {
echo("<b>" . $i . $user->item($i)->nodeName . ":</b> ");
echo($user->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
}
?>
The above PHP works fine but... its PHP and its not written to live feed. I have a working jQuery solution below but I can't seem to implement it correctly with the first JS script above. As you can see right now the above JS script is triggering a GET request and expecting a feed from the PHP file. Here is my jQuery AJAX script:
setInterval(updateMe2,500);
function updateMe2(){
$.ajax({
type: "GET",
url: "../Administration/data/people.xml"
}).done(function (xml) {
$("#txtHint").empty();
$(xml).find('person').each(function() {
var firstName = $(xml).find('firstName').text();
var lastName = $(xml).find('lastName').text();
var age = $(xml).find('age').text();
var hometown = $(xml).find('hometown').text();
var job = $(xml).find('job').text();
$('<b></b>').html(firstName).appendTo('#loadMe');
$('<b></b>').html(lastName).appendTo('#loadMe');
$('<b></b>').html(age).appendTo('#loadMe');
$('<b></b>').html(hometown).appendTo('#loadMe');
$('<b></b>').html(job).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
};
How can I change the first JS snippet to work with this, above jQuery snippet instead of the above PHP file? NOTE: both the PHP file and the jQuery script both spit out the same markup, the PHP file is just written much differently. Thanks a ton in advance!
I created a solution if anyone is interested:
setInterval(itemMenu,1500);
function itemMenu() {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$("#loadMe").empty();
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
$('<button type="button" onclick="itemContent(this.value)"></button>').attr('value', fullName).html(fullName).appendTo('#loadMe');
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
//setInterval(itemContent,1500);
function itemContent(q) {
$.ajax({
type: "GET",
url: "people.xml"
}).done(function (xml) {
$(xml).find('fullName').each(function() {
var fullName = $(this).text();
if(q==fullName) {
$("#toadMe").empty();
firstName = $(this).siblings('firstName');
lastName = $(this).siblings('lastName');
age = $(this).siblings('age');
hometown = $(this).siblings('hometown');
job = $(this).siblings('job');
$('<h1></h1>').html(firstName).appendTo('#toadMe');
$('<h1></h1>').html(lastName).appendTo('#toadMe');
$('<h1></h1>').html(age).appendTo('#toadMe');
$('<h1></h1>').html(hometown).appendTo('#toadMe');
$('<h1></h1>').html(job).appendTo('#toadMe');
}
});
}).fail(function (response, error) {
$('#info').text('Error!');
});
};
$('#show_mess').click(function (){
$('#dropdown_mess').slideToggle("slow");
$('#arrow_mess').slideToggle("slow");
$('#arrow_not').hide("slow");
$('#dropdown_not').hide("slow");
function recall(){ setTimeout(function () {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/ajax/mess_data.php", true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('dropdown_mess').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send();
document.getElementById('dropdown_mess').innerHTML = "<img class='non_auto' id='ajax_loading' src='img/ajax_loading.gif'></img>";
recall();
}, 2000);
};
recall();
});
this function works fine but when each ajax call is done i need to colse and re-oper chrome in order to work, works fine in firefox
You are already using Jquery so why don't you try it's ajax function like below
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
....
});
You can find more information on the manual