I want to create a edit pop up form using just ajax. i.e when user clicks on a link , a pop up comes up and he edits the data and saves it. can i do this with out any ajax framework ?
Yes you can, you can always create XMLHttpRequest objects yourself, but using a framework will save you hours or days of coding and make sure your service has maximum browser compatibility.
Yes, you can use the following function which I wrote and did several weeks optimizing it.
function ajaxGET(url,span_or_div) {
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType('text/plain');
}
}
else if (window.ActiveXObject) { // IE ( yeah 200bytes wasted because of IE.. lol
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 1) {
window.document.getElementById(span_or_div).innerHTML='Loading...';
}
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
document.getElementById(span_or_div).innerHTML=(httpRequest.responseText);
} else {
window.document.getElementById(span_or_div).innerHTML='<strong>Error 404</strong><br />Page Not Found.';
}
}
};
httpRequest.open('GET', url, true);
httpRequest.send('');
}
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?
Quick notes. I am not using jQuery so don't suggest it.
When pressing the button which has the onclick="ajaxfunction();" i get an alert saying "Error during AJAX call. Please try again " and then I get the alert saying success, twice :S ... Why is this happening?
I don't understand why this is happening, as it calls the error, and then goes to the other part of the if statement...
Thanks in advance!
<script>
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
var url="insertProduct.php";
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var name = document.getElementById("name");
var code = document.getElementById("code");
xmlhttp.open("POST",url,true); //calling insertProduct.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("name=" + encodeURIComponent(name.value) + "&code=" + encodeURIComponent(code.value)); //Posting to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
alert("Success");
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again " + xmlhttp.status);
}
}
</script>
After finishing the task you can call return;
Likes below.
function handleServerResponse() {
if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
alert("Success");
document.getElementById("message").innerHTML=xmlhttp.responseText;
return;
}
else {
alert("Error during AJAX call. Please try again " + xmlhttp.status);
return;
}
}
I hope this will help to you.
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
So I've got an AJAX project which uses the XmlHttpRequest object to dynamically retrieve data from the server-side (in my case, I use JSON with PHP/MySQL in case that's relevant). Pretty much all my HTML elements are created dynamically via the javascript DOM, so it's the .js files doing the work.
Here's a typical .js file I use to get server-side info from PHP and then build the html:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for(var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++) {
try {
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
} catch(e) {}
}
}
if (!xmlHttp) alert("Error creating XmlHttpRequest object.");
else { return xmlHttp; }
}
function initialize_main() {
if (xmlHttp) {
try {
xmlHttp.open("GET", "main_php.php", true);
xmlHttp.onreadystatechange = handleMainStateChange; //call a function when the state changes
xmlHttp.send(null);
} catch(e) {
alert("Can't connect to server: " + e.toString());
}
}
}
function handleMainStateChange() {
if (xmlHttp.readyState==4) {
if (xmlHttp.status==200) {
try {
init_main();
} catch(e) {
alert("Error reading the response: " + e.toString());
}
} else {
alert("There was a problem retrieving data: " + xmlHttp.statusText);
}
}
}
function init_main() {
var data = JSON.parse(xmlHttp.responseText);
//now do stuff with the DOM or w/e
}
So as I said everything is cool in firefox and chrome. But internet explorer tells me: "Error reading the response: TypeError: Object doesn't support this property or method". I'm a bit new to AJAX as you might guess, so thanks for any help!
I would highly recommend that you use JQuery so that you can write Javascript that doesn't care about the type of browser (JQuery does this for you): http://jquery.com/
Try using this function, for me it works for all browser
function getXMLHTTP()
{
var xmlhttp = false;
try
{
xmlhttp = new XMLHttpRequest();
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1)
{
xmlhttp = false;
}
}
}
return xmlhttp;
}
How can I use javascript to send a one way message to php? I would like to get the browser information from javascript and just send it to php in the background. I know I can get some of this from php, but I'd rather use javascript. Is there a way to do this without a framework like jquery?
Yes, you can do it with something like this:
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
alert('Here goes something');
self.xmlHttpReq.send('browser info here');
}
}
}
This will send "browser info here" as POST in the php page you pass to the function as url. I didnt test it though
You would have to submit an AJAX request to a PHP script. Yes, you could do it without using a framework but I wouldn't advise it.
You need to make an AJAX call to a PHP page, preferably using POST. Any data you want to send needs to be sent along with the request.
I recommend using a framework such as jQuery, but if you insist on using raw JavaScript, you want to research XMLHttpRequest.
// fix for older IE versions
// see http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
if( typeof window.XMLHttpRequest === 'undefined' &&
typeof window.ActiveXObject === 'function') {
window.XMLHttpRequest = function() {
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
return new ActiveXObject('Microsoft.XMLHTTP');
};
}
function postData(url, data, errhandler) {
var req = new XMLHttpRequest;
req.onreadystatechange = function() {
if(this.readyState === 4 && this.status !== 200 && errhandler)
errhandler(this);
};
try {
req.open('POST', url, true); // async post request
req.send(data);
}
catch(e) {
if(errhandler)
errhandler(req);
}
}