How can I load html in a div when I click a button?
I have function but it does not work:
function ajaxFunction(id, url){
document.getElementById("sh").style.visibility = 'hidden';
var xmlHttp;
try {// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
//Get the response from the server and extract the section that comes in the body section of the second html page avoid inserting the header part of the second page in your first page's element
var respText = xmlHttp.responseText.split('<body>');
elem.innerHTML = respText[1].split('</body>')[0];
}
}
var elem = document.getElementById(id);
if (!elem) {
alert('The element with the passed ID doesn\'t exists in your page');
return;
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
And I have button to click it.
<button type="button" name="new metere" value="" class="button" onclick="ajaxFunction('test','newmetere.html');">new metere</button>
when I put newmetere.php Function does not work and get garbage value.
Try jQuery's load () : it's a fast and simple way to load content from another page asynchronously in a web page using Ajax!
Related
Learning AJAX.
I have the following AJAX script, i am using it primarily for navigation (backend php):
function ajaxFunction(linked) {
var ajaxRequest;
var loading = $('#loading');
if(loading.length > 0) {
loading.css('display', 'block');
}
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function() { **//READY STATE HERE!**
if(ajaxRequest.readyState == 4) {
var ajaxDisplay = $('#wrapper');
loading.css('display', 'none');
ajaxDisplay.html(ajaxRequest.responseText);
if($('#search_field').length > 0) {
$('#search_field').focus();
}
if($('#year').length > 0) {
$('html').scrollTo('#year');
}
startValidation(); **// VALIDATION FUNCTION HERE!**
}
}
// Now get the value from user and pass it to
// server script.
if(linked == 'addNewPage' || linked == 'add') {
var queryString = "?page=add";
queryString += "&action=customer&add=new&ajax=ajaxRequest";
} else if(){} etc...
I have downloaded the h5validate plugin to take advantage of the HTML5 validation i already have in place, the problem is when i load the content through AJAX any .ready functions get unbound from the DOM and don't work. I have tried calling the function after ReadyState==4 but it still won't launch. The function works if i navigate to it directly (without AJAX) and use:
window.onload = startValidation();
Validate trigger:
function startValidation() {
$('.row').h5Validate({
errorClass:'red'
});
}
Where am i going wrong here?
I'm using the following to update a DIV called 'output'. This works fine with one exception, I would like echo entries to update the parent page.
<script type="text/javascript">
<!--
var divid = 'output';
var loadingmessage = '<img src="working.gif">';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
This is called using :
<input type='button' name='Send' value='submit' onclick="javascript: formget(this.form, 'foo.php');">
The issue I have is foo.php runs a series of exec() commands, between each command is an echo statement that I would like to be displayed in the output div.
So it will do something like:
echo "archive files";
exec ("tar -cvf bar.tar bar.txt foo.txt");
echo "backing up /user";
exec ("tar -cvf /user.tar /user/*");
I would like the user to see the working.gif, but under it each echo statement from foo.php
Can that be done and how ?
Thanks
I can't say I've ever tried sending back chunks of data at separate times with a single AJAX request, so I'm not sure it's possible. What happens currently? Do you only get first echoed message, or do only get the entire response at the end?
Two things that I know will work:
Break your PHP script into multiple scripts and execute them in order with separate AJAX requests. This will only work if the separated scripts don't depend on each other or you find some other way to persist the state across the separated scripts.
Create an iframe and load the PHP script into it instead of using an AJAX request. Flushing the output of the PHP script should then work. (If you have ever used Wordpress, I believe they use this technique to show the progress of plugin updates.)
I have a php function in which some pdf is being created. I have a button and I want to call that function on button click and then redirecting to a url. What can be the simplest method of doing that?
If you need to call a PHP method, I'd use AJAX. Something like this:
var btn = document.getElementById("button_id");
btn.onclick = function () {
// Make AJAX request
// On success, do this:
window.location.href = "url to redirect to";
};
The code for "Make AJAX request" can be Googled easily, and I will provide it in a minute :)
UPDATE:
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Firefox, Chrome, Opera 8.0+, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP.6.0");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP.3.0");
} catch (e) {
throw new Error("This browser does not support XMLHttpRequest.");
}
}
}
}
}
return ajaxRequest;
}
The AJAX code -
var req = ajaxFunction();
req.onreadystatechange = function (response) {
if (response.status == 200 && response.readyState == 4) {
window.location.href = "url to redirect to";
}
}
req.open("POST", "your PHP file's URL", true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(null); // Or send any `key=value&` pairs as a string
There are various ways to accomplish this. I would call the PHP function in ajax and redirect based on the functions return value. The following example uses jQuery:
jQuery:
$.ajax({
url: 'createpdf.php',
success: function(data) {
if (data) window.location = 'link/to/new/path';
}
});
PHP:
function create_pdf(){
//Create PDF
//If PDF was created successfully, return true
return true;
}
<form name="input" action="whatever.php" method="get">
...
<input type="submit" value="Submit">
</form>
I have <form> on my page containing a <textarea>, and I want to send the text entered in it using Ajax. The text goes to a PHP page, where I insert it into a SQL database.
The problem I am facing is that whenever I write + or & in the <textarea>, JavaScript treats them as special characters in the URL. How can I escape them?
function getMessageResponse() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch(e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
document.getElementById('response').innerHTML = xmlHttp.responseText;
document.myform.post.value = '';
retrieve();
}
}
var url = "wall4.php";
url = url+"?post=" + document.myform.post.value;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
Encode your parameter:
url = url + "?post=" + encodeURIComponent(document.myform.post.value);
I posting my value through ajax and using the response the details will be displayed.I am getting the problem while retreiving the data.But i dono where i have mistaked,then this is the error getiing displayed frequently
"There was a problem while using XMLHTTP:\n";
in all browsers mainly in the chrome,could any one help me...
this is my code,
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer 6+
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// Internet Eplorer 5
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX. Download a newer browser to view this page.");
return false;
}
}
}
// insert server response into HTML element
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
MM_check_session(xmlHttp.responseText);
var b_gc = document.getElementById(insert).value;
document.getElementById(insert).value = xmlHttp.responseText;
var shippingid = getCheckedValue('checkout_form', 'shippingid');
closeMessage();
MM_calc_shipping(shippingid);
if (b_gc == xmlHttp.responseText) {
MM_register();
} else {
error = 1;
document.getElementById('payment_error').innerHTML = xmlHttp.responseText;
document.getElementById(insert).value = '';
}
} else {
closeMessage();
alert("We can't process your request.Please refresh(reload) the page to proceed further:\n"
+ xmlHttp.statusText);
}
}
}
displayStaticMessage(
'<img src=' + config_MM_loader_image_path + ' alt=\'loading...Please wait\'>',
false);
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader('Content-length', parameters.length);
xmlHttp.setRequestHeader('Connection', 'close');
xmlHttp.send(parameters);
any help
You seem to be incorrectly tagged as php. Also have you considered jQuery for the ease of ajax whilst using it.
as for your question could you post the code on the page where the ajax request is going to as the code here looks fine..
Edit:
Where is serverScript set?
change serverScript for the ajax page you are calling?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849%28v=vs.85%29.aspx