I've been trying to get ajax to work the whole day and this my last hope, i wrote a simple test to see if i get any response, the xhr.status is 0 instead of 200, and the xhr.responseText is undefinded. I call a simple (php file) which generates a json object, my code is as follows(i tried using $.ajax but it didnt help either):
$(function(){
$('#checkin').click(function(){
var ajaxRequest;
var connection = ajaxFunction();
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
ajaxRequest.open("GET", "places.php", true);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(console.error(ajaxRequest.status));
}
}
ajaxRequest.send(null);
}
});
})
and my php file is as follows:
<?php
header('Content-type: application/json');
require "SQLquery.php";
$places = new SQLquery;
$places->db_query("SELECT * FROM places");
echo json_encode($places->results);
?>
any help will be much appreciated. Thanx
Here is a simple implementation using jQuery's $.ajax() and json.
Javascript:
function sendAjax() {
// The data you want to pass to places.php
var params = {
'checkin' : true
};
// Construct the call
ajax = $.ajax({
url: '/places.php',
type: 'GET',
data: params,
dataType: 'json'
});
// Send it and say which function you'll
// use to handle the response
ajax.done(sendAjaxDone);
}
// Handle the response
function sendAjaxDone(response) {
console.log(response);
}
places.php
header('Content-type: application/json');
require "SQLquery.php";
if ($_GET['checkin']) {
$places = new SQLquery;
$places->db_query("SELECT * FROM places");
echo json_encode($places->results);
}
Related
I am trying to write a google ads like javaScript plugin. I can not use jQuery ajax as it should be working fine for all sites.
Here is my JavaScript code.
var ajaxRequest; // The variable that makes Ajax possible!
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert( ajaxRequest.responseText);
console.log('xhr',ajaxRequest)
} else {
//alert(ajaxRequest.readyState);
//alert(ajaxRequest.responseText);
}
}
var project_path = "http://www.domainname.com/"; //for stackoverflow, using right path in live code.
var req_url = project_path + "ads/verifypublisher/";
ajaxRequest.open("GET", req_url, true);
ajaxRequest.send(null);
And here is how my PHP file looks like,
echo("<b>hi:</b> ");
exit();
Yes, thats all i have there. Still responseText is empty. What am i missing here?
alert(req_url) should show wrong url "http://www.domainname.comads/verifypublisher/"
It's better to make sure the status code is 200 before doing anything with the response. Then you can spot problems earlier.
try this in my test it work in most of browser
var responseText=function(e,doing){
if (e.readyState== 4) {
if(doing)doing(e);
return(e.responseText);
};
if (e.readyState == 200) {
if(doing)doing(e);
return(e.responseText);
};
return false;
};
function loadXMLPostDocf(url,method,posData,uploadProgress,uploadComplete,uploadFailed,uploadCanceled,statechange,CallBackOnSend) {
var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest && checkVersion()) {
pos = new XMLHttpRequest();
pos.open(method, url, true);
//pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if(statechange!=''){pos.onreadystatechange = statechange;};
try{
if(uploadProgress!='')if(pos.upload){
pos.upload.addEventListener("progress", uploadProgress, true);
}else{
pos.addEventListener("progress", uploadProgress, true);
}
if(uploadComplete!='')pos.addEventListener("load", uploadComplete, false);
if(uploadFailed!='')pos.addEventListener("error", uploadFailed, false);
if(uploadCanceled!='')pos.addEventListener("abort", uploadCanceled, false);
}catch(e){
}
pos.send(posData);
if(CallBackOnSend)CallBackOnSend(pos);
//console.log(pos.abort());
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
for (var i=0; i < arrSignatures.length; i++) {
try {
pos = new ActiveXObject(arrSignatures[i]);
} catch (oError) {
//ignore
};
};
if (pos) {
pos.open(method, url, false);
//pos.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if(!statechange){pos.onreadystatechange = statechange;};
if(!uploadComplete){pos.onreadystatechange = uploadComplete;};
// if(uploadProgress!='')pos.upload.addEventListener("progress", uploadProgress, true);
//if(uploadComplete!='')pos.addEventListener("load", uploadComplete, false);
//if(uploadFailed!='')pos.addEventListener("error", uploadFailed, false);
//if(uploadCanceled!='')pos.addEventListener("abort", uploadCanceled, false);
pos.send(posData);
if(CallBackOnSend)CallBackOnSend(pos);
};
};
return(pos);
};
sample:
var complete=function(e){
var Body=responseText(e.target);
console.log(Body);
};
var uploadProgress=function(evt){
};
var uploadComplete=function(evt){
if(evt.target.status==200 || evt.target.status==304){
var Body=responseText(evt.target);
console.log(Body);
}else{
return false;
};
};
var uploadFailed=function(evt){
};
var uploadCanceled=function(evt){
};
var CallBackOnSend=function(evt){
};
loadXMLPostDocf("http://domain.com/index.php","GET",null,uploadProgress,uploadComplete,uploadFailed,uploadCanceled,complete,CallBackOnSend);
My problem similar to this was solved by checking my html code. I was having an onclick handler in my form submit button to a method. like this : onclick="sendFalconRequestWithHeaders()". This method in turn calls ajax just like yours, and does what I want. But not as expected, my browser was returning nothing.
Learned From someone's hardwork, I have returned false in this handler, and solved.
Let me mention that before arriving to this post, I have spent a whole 3-day weekend and a half day in office writing code implementing CORS filters, jetty config, other jersey and embedded jetty related stuff - just to fix this., revolving all my understanding around cross domain ajax requests and standards stuff. It was ridiculous how simple mistakes in javascript make you dumb.
Now I have to clean my code to submit git patch cleanly. Thanks to that someone.
I am using AJAX function. I am passing 3 variables to the next page using AJAX. When I add the 4th variable the function doesn't get called.
Code:
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var count = document.getElementById('count').value;
var type = document.getElementById('type').value;
var sem = document.getElementById('sem').value;
var rid = document.getElementById('room').value;
ajaxRequest.open("GET", "add_requi_ajax.php?count=" + count+"&type="+ type+"&sem="+sem+"&rid="+rid, true);
ajaxRequest.send(null);
};
</script>
Your code is syntactically and logically correct, which means that the problem is likely one of your input IDs is wrong (typo? Should room be rid?), or you call the function before the inputs are rendered on the page (use window.onload).
Verify each of your input IDs. If they all look correct, then comment them out and hard code the values to rule out your inputs as a problem. Watch the error console for any error messages. If an uncaught error is encountered, it can appear that the function isn't being called.
You probably need to urlencode your values.
i have page that do add new record by old way ajax, this code was add new record and return the error or done result message , how can i print the message on div and print result on other div. i try but some one tell me to use JOSN, how can i do that
<script language="JavaScript">
$(document).ready(function() {
});
$("#closeerr").live('click', function() {
$("#gadget").hide();
});
var HttPRequest = false;
function doCallAjax(Mode,Page,ID) {
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = 'AjaxItemsGroupsRecord.php';
var pmeters = "titems_groups_GroupName=" + encodeURI( document.getElementById("items_groups_GroupName").value) +
"&titems_groups_sys_type_ID=" + encodeURI( document.getElementById("items_groups_sys_type_ID").value ) +
'&myPage='+Page +
"&tID=" + ID +
"&tMode=" + Mode;
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "looding";
}
if(HttPRequest.readyState == 4) // Return Request
{
document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
}
}
}
</script>
If jQuery is an option... As mentioned in my comment I'd recommend you try out jQuery http://jquery.com/ as you look to be fairly new to JavaScript.
It makes AJAX requests a lot simpler and you don't have to worry about making XMLHttpRequest work cross browser.
For making an actual AJAX request see: http://api.jquery.com/jQuery.ajax/
Now if you want to use JSON you need to convert the data to return in your PHP script.
This is really easy, you just pass the data in json_encode() and it will convert the data to a JSON string. You then just echo it out so that it's returned to the AJAX request.
echo json_encode($data);
Now if you've setup your AJAX request to expect a JSON response then you can use the data that comes back. So something like this:
$.ajax({
url: 'request.php', // the php you want to call
dataType: 'json' // the type of data being returned
}).done(function(json) {
// you now have a json object
});
If you can only use native JavaScript...
If you can't use jQuery then it roughly works the same way. You'd have the code in your example for the AJAX request. You'd still use json_encode() in the PHP. The only difference is when the data comes back you'd need to parse it like so:
JSON.parse(json);
For more info on this last bit checkout: Parse JSON in JavaScript?
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>
function ajaxFunction(phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.subCat').html(ajaxRequest.responseText);
$('.subCat').ready(function(){
$('.subCat').fadeIn();
});
}
}
var url = "products.php?func=" + phpFunction;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
This function works great, and has no problems. But if I add:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
});
}
}
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
When I try to execute ajaxFunction('returnAllProducts') I get:
syntax error
});\n
from
$('.' + idNum).html(ajaxRequest.responseText);
}); <<<----
and
ajaxFunction is not defined
javascript:ajaxFunction('returnAllProducts')()
So my questions are:
a) how do I convert this over to jquery? I've read over some jquery ajax tutorials, but I wasn't able to make the connection how to do what I am doing here.
b) How do I get both functions to work? I know the PHP behind them works fine, but I can't even test if refreshProduct() works properly right now.
You seem to be missing a }
this is your code, properly indented...
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
});
When it should be
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
}
});
Also, the two } after this should be deleted, rendering your code like this:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
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
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
}
});
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
As for rewriting this using jQuery, it's really easy:
function ajaxFunction(phpFunction){
var url = "products.php?func=" + phpFunction;
$.get(url, function(data) {
$('.subCat').html(data).ready(function(){
$('.subCat').fadeIn();
});
});
}
function refreshProduct(idNum, phpFunction){
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
$.get(url, function(data) {
$('.' + idNum).empty().html(data);
});
}