I want to use AJAX to replace the contents of a div. Although the application is fairly complex, I have tried to dumb it down in isolation so that I can get the basic concept working first.
For now, I just want to replace a div as per the PHP file...
<?php
$id = $_GET['id'];
if ($id = 1)
{
$text = 'This is some text';
}
elseif ($id = 2) {
{
$text = 'This is a lot more text than the first text!';
}
elseif ($id = 3) {
{
$text = 'This is a lot more text than the first text, and a load more than the third as well!!';
}
echo $text;
?>
Fairly simple stuff really. So here's my HTML file...
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">I want this content replacing</div>
ID: 1<br>
ID: 2<br>
ID: 3
</body>
</html>
I realise what is there will never work as I've modified some stuff I found online, but basically I'm looking to pass a variable such as the ID in the link to the AJAX script to replace the contents of the div.
How do I get this working? Is there a better alternative to using <a> tags?
Using jQuery
Your HTML
ID: 1
Javascript
// Delegate click event
$(document).on('click', 'a.ajax', function(){
var el = $(this);
$.ajax({
url: 'ajax.php',
data: {id: el.data('id')},
}).done(function(response){
$('#myDiv').html(response);
});
return false;
});
I'll answer your question using Vanilla JavaScript rather than using the jQuery AJAX Helper. Although it's very good - but learning the Vanilla way will give you a good idea of what the libraries do to aid you.
Firstly, you are making an Ajax call but albeit, an Empty one.
"Query" parameters is what $_GET is based on, are formated like:
?Key=Value&KeyTwo=SomeOtherValue
Which in PHP, Translates too:
Array
(
[Key] => Value
[KeyTwo] => SomeOtherValue
)
This'll need to be passed along with the xmlhttp.send() for it to make an successful ajax call, with Data.
But to collect this data in the first place, you must collect it with your HTML:
<!-- Notice how the <a> tags now have attributes attached, the id="" -->
ID: 1<br />
ID: 2
<script>
function loadXMLDoc( Id ) {
/**
* Id is the <a href="#" id="3" collected
* when onclick="loadXMLDoc()" is pressed
**/
var xmlhttp,
DataId = Id.attributes.id.value;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
/**
* Notice the ?id="+ dataId +"
* It's passing through the ID Collected
**/
xmlhttp.open("GET","ajax.php?id="+ dataId +"",true);
xmlhttp.send();
}
</script>
Although this code above is very inefficient, you would be much better in JavaScript & Programming in general to keep things generic. By modifying your code to:
ID: 1<br />
ID: 2
<script>
function getId() {
alert( this.attributes.id.value );
//Click on id="2", alerts '2'
}
/**
* We find all the HTML tags with the
* attribute that has 'class="idlistener"
* attached, we 'bind' it to a function called
* getId()
**/
var IdListener = document.getElementsByClassName('idlistener');
for( var x = 0; x < IdListener.length; x++ ) {
IdListener[x].addEventListener( 'click', getId, false );
}
</script>
Demo: Fiddle
Lastly, It does look to me you've discovered this AJAX Code from W3Schools.com. I think you'll find every StackOverflow Web Developer that would agree with me - Don't learn from this Site!
General format for replacing html content with the response from an ajax call:
$.ajax({
url: yourUrl,
method: 'get', // or 'post'
success: function (response) {
$('#myDiv').html(response);
}
// other ajax options here if you need them
});
You dont need to use ajax for that. Just use the following in the condition. Dont forget to call the jquery js file on the header. Otherwise jquery wont work:
echo '<script>$("#myDiv").html("This is some text")</script>';
Related
First question on StackOverflow so I hope i get this right. I have a AJAX call to a JS function :
function addOptionText(str)
{
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","AddText.php?q="+str,true);
xmlhttp.send();
}
And Here is my HTML code :
<body>
<FORM NAME ="form6" onclick= "addOptionText(this.value)" >
Text Input:
<INPUT TYPE = "TEXT" VALUE placeholder ="Nume Field" NAME ="Text_Field">
<INPUT TYPE = "Submit" Name = "Edit" VALUE = "Add" >
</FORM>
<p id="0"> </p>
</body>
The php file only contains :
<html>
<body>
<?php
$name = ($_GET['q']);
echo "nume";
?>
</body>
</html>
But the function doesn't appear to be used as the paragraph doesn't change. New to php here and trying to understand how it works so I'm thinking something might've slipped me.
EDIT
I had more than one "submit" id's so that's why it didn't work. I changed the "submit" id from to and now all's working as intended.
Unfortunately, your code is all over the place.
<FORM NAME ="form6" onclick= "addOptionText(this.value)" > is wrong for a multitude of reasons.
First, we don't use onclick on the form itself but on the submit button. Secondly the value you put in the parameter doesn't in any way represent the value of the text box.
Since you want just to display the value of your textbox and not to navigate to a different page, modify your <form> tag, so that it doesn't have an action = "some page" attribute, because that way it will automatically redirect you to the page you specify and thus the AJAX request is rendered useless. Instead, modify your tag so that it looks like this:
<form name = "form6" onsubmit = "return false;">Provided that you specify your input/button type to submit: type= "submit", using the onsubmit event and setting it to return false will prevent the form from sending you over to a new page.
When using Vanilla JavaScript and not jQuery, I believe its more efficient to use IDs, so as to identify your HTML elements easier in JavaScript.
Your PHP code doesn't mean anything at all. Before doing anything else, you need to evaluate if, indeed, the q was sent over to the PHP file with the GET method. To do that, use in your php file:if (isset($_GET["q"])): // Your codeendif;
The line: echo "nume" you wrote will output "nume" regardless of what you have actually sent to your php file with the AJAX request.
In my opinion is pretty useless to still provide support for Internet Explorer 5 and 6. Not many people use it, unless for whatever reason they are mentally bound to it.
Analytically, how your files should be:
HTML:
<body>
<form name = "form6" onsubmit = "return false;">
Text Input:
<input type = "TEXT" placeholder ="Nume Field" id = "textfield" name = "Text_Field"/>
<input id = "submit" type= "submit" Name = "Edit" value= "Add"/>
</form>
<p id = "0"> </p>
<script src = "YOUR JAVASCRIPT FILE" type = "text/javascript"></script>
</body>
JavaScript:
var textfield = document.getElementById("textfield");
var submit = document.getElementById("submit");
submit.onclick = function() {
'use strict';
var xmlhttp;
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("0").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "AddText.php?q=" + textfield.value, true);
xmlhttp.send();
};
PHP:
<?php
if (isset($_GET["q"])):
echo ($_GET["q"]);
endif;
?>
I'm doing an assigment for my programming class. I need to show a table with two columns (name and lastname) of a list of friends. This data is stored in a XML file like this:
<?xml version='1.0' standalone='yes'?>
<amigos>
<amigo>
<nombre>Alejandra</nombre>
<apellido>Ponce</apellido>
</amigo>
<amigo>
<nombre>Dalia</nombre>
<apellido>Gordon</apellido>
</amigo>
I retrieve this data with php, like this:
<table width="200" border="1">
<tr align="center">
<td>NOMBRE</td>
<td>APELLIDO</td>
</tr>
<?php
$amigos = simplexml_load_file('listaamigos.xml');
foreach ($amigos->amigo as $amigo) {
echo '<tr>';
echo '<td>',$amigo->nombre,'</td>';
echo '<td>',$amigo->apellido,'</td>';
echo '</tr>';
}
?>
I call this php file with a function written in javascript language. I'm using ajax for this homework. My javascript file is the one I'm showing below:
var xmlHttp;
function createXmlHttpRequestObject() {
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp=false;
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp=false;
}
}
if(!xmlHttp)
alert('Can't connect to the host');
else
return xmlHttp;
}
function cargarAmigos(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function cargar(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function procesarEventos()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("listaAmigos").innerHTML= xmlHttp.responseText;
}
}
I use this javascript file in a html file. I call the function cargar () in the button's onclick event, like this:
<body>
<div id="listaAmigos" >
Lista amigos
</div>
<button onclick="cargarAmigos('procedimiento.php');">Lista Amigos Ajax</button>
</body>
The problem is that the code is not working. I mean that the names are not displaying at all in the table. Actually the table does not appear.
I'm pretty sure that the error is not in the code because it was working last week and I haven't changed the code since then. But today I loaded the html page just for "fun" and it wasn't showing my list of friends.
So I decided to open another project with uses the same algorithm and this one is not working too. I've checked that all the files are in the same folder. I've checked my xammp server and it's apache and mysql services are on. I have no idea what "thing" I could have done to cause this problem.
Any help will be really appreciated.
It looks like you should escape the ' character in this line:
alert('Can't connect to the host');
i.e. rewrite it like
alert("Can't connect to the host");
You can see that there's an error even just by looking at the formatting on Stack Overflow :)
Please refer to this question for the details on why it's working like that: When to use double or single quotes in JavaScript?
I have a standard html page index.php and within this page I have a
<div id="alertMe">...</div>
I use a simple onclick function to do an AJAX change of this div. I wont paste the whole Ajax call.
xmlhttp.open("GET","message.php?msg=hello" , true);
message.php loads and I can display the $_GET['msg'] value in the alertMe div. However, I have a simple javascript alert which is in the file message.php
<script type="text/javascript">
alert("I am an alert box!");
</script>
I cannot get the alert to popup. Is this because I am trying to run javascript within a div load? I would have thought that was a common requirement.
Any ideas?
==== Including files =====
index.php
<html>
<script>
function loadMsg(moduleID) {
var xmlhttp;
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("alertMe").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","message.php?msg=hello" , true);
xmlhttp.send();
}
</script>
<body>
<div id="alertMe"></div>
Load Message
</body>
</html>
message.php
<?php
echo $_GET['msg'];?>
<script type="text/javascript">
alert("I am an alert box!");
</script>
As some of the commentators have pointed out, <script>s inside an AJAX response do not get executed when the HTML is injected into the page by setting the innerHTML property of a DOM node. If you really need to execute those scripts:
function setHtml(element, html) {
element.innerHTML = html;
var scripts = element.getElementsByTagName("script"),
i = 0, script;
for (i; i < scripts.length; i++) {
script = scripts[i];
if (script.type = "text/javascript" && !script.src) {
eval(script.innerHTML);
}
}
}
Edit: I personally recommend against this. The "success" handler for your AJAX call should contain the logic you need to run post-AJAX.
I am using below code on my main page ,where other pages are loaded using ajax with the help of TWO RADIO BUTTONS
<script>
function loadXMLDoc(str)
{
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
if(str=="Candidate")
{
xmlhttp.open("GET","creg.php",true);
}
else if(str=="Employer")
{
xmlhttp.open("GET","Empyr.php",true);
}
xmlhttp.send();
}
</script>
below script is written for FORM VALIDATION (written at end of main page),this script works only when main page loaded first time ,but when forms are getting loaded second time using ajax than this script is not working
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
As i know script is getting read at the time of page load ,but now Where should I write this script so that it works when I load forms using ajax,where i am going wrong?
Are you using validation engine? I will not prefere doing ajax call with pure javascript it looks messy.
jQuery(document).ready(function($) {
$('#registration').validate({
rules:{
email: {
email: true
},
password : {
minlength : 6
},
repassword : {
minlength : 6,
equalTo : "#password"
}
},
submitHandler: function(form) {
// do other things for a valid form
var post = {};
form_data = $(form).serialize();
//console.log(form_data);
//console.log(book_form);
if(post)
{
$.post(site_url+'/members/register',form_data,
function(response){
var res1 = $.parseJSON(response);
console.log(res1);
if(res1.success == true )
{
$('.success_message').html('You are successfully registered ').show();
window.location.href = site_url+'/pages/registerstep';
clear_form(form);
}
else
{
$('.error_message').html(res1.success).show();
//clear_form(form);
}
}
);
}
}
});
});
Use something like this. This will work. Reason why your code is not working after first load is because your validation is not triggering while form submit
You need to run the code again to bind the event handler, after the new element is inserted into the DOM. It is better to use cross platform javascript framework like jQuery, Prototypejs etc
You need to call the bellow javascript again from ajax response
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
Check here
I am using CodeIgniter ..I can't access the method from the controller
I have this script in my view
<script>
function showHint(str){
if (str.length==0){
document.getElementById("txtHint").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/ajaxSearch",true);
xmlhttp.send();
}
</script>
and i have a controller named ajax with a method ajaxSearch()
public function ajaxSearch(){
echo "received";
}
Folder Structure
htdocs/
AjaxTry/
AjaxSearchingMVC/
application/
controller/
ajax.php //controller
ajaxSearch() //method
views/
view_ajax.php // here is where the script is written
What could be the possible problem here?
What I have been using in my project for ajax request is forming the Ajax URL like the following:
Inside your view put a global variable, inside the head, with the value set to base_url() like so:
var base_url = <?php echo base_url(); ?>
Now inside your script, call this controller action, that you are trying to access, using the base_url like so:
xmlhttp.open("GET", base_url + "ajax/ajaxSearch",true);
This would create your ajax URL like http://yourbaseurl/ajax/ajaxSearch and hopefully solve the problem for you!
NOTE
Your base_url must be something like http://localhost/yourprojectfolder/ for this to work
Do the following...
In controller create example.php and leave ajax.php like it is. And in views leave like you have already view_ajax.php
We are going to load data from example.php with Ajax
Your ajax.php should look like this
class ajax extends CI_Controller {
public function index()
{
$this->load->helper('url'); // if you are going to use helpher don't forget to load it ( of course if you are not loading it by default )
$this->load->view('view_ajax.php'); // in `view_ajax.php` you must have JavaScript code
}
}
JavaScript code for testing purpose write like
<script>
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
console.log(xmlhttp.responseText);// you will see OKKK in console
}
}
xmlhttp.open("GET","../index.php/example",true); // first try `../index.php/example` ( extension depends if you enable/disable url rewrite in apache.conf ) , if this won't work then try base_url/index.php/example ( where you can specify base_url by static or with CodeIgniter helpher function )
xmlhttp.send();
</script>
Nest Step
example.php should look like this
class example extends CI_Controller {
public function index()
{
echo "OKKK";
}
}
Add the following function in the JS script
function FetchData() {
var valueFromClient = document.getElementById("ReplaceWithID").value;
alert("Received from client:"+valueFromClient );
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert("Received from server:"+this.responseText);
}
};
xmlhttp.open("POST", "http://localhost:52322/ControllerName/MethodName?CurrentC=" + valueFromClient , true);
xmlhttp.send();
}
Change the Port : 52322 according to your port number.
Its a localhost. So you may have to change it once your site goes online.
on the View. Add onChange(FetchData())
For Example:
<select id="AnyIDHERE" onchange="updateProvince()"> </select>