Good day to all. I have the flowing problem.
I have 2 domains. On one domain I send an ajax post to the other and expect some results. The problem is that the response is always empty. If I inspect the net tab the request looks alright (the post data is fine), it doesn't receive any error, it ends (I put an alert on the handle response function to check what the response is). I tried sending a request to random domains (like example.com) to see if I get anything. The response is the same... none.
Here is the script I use:
function sendReqPost(url) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
//http_request.onreadystatechange = handleResponseAccept;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
//parameters is a global variable with the post data.
http_request.send(parameters);
}
I double checked everything in the script... I also inserted echos in the requested php page to see if I get anything. Whatever I do the response is empty.
P.S. On another domain the ajax script worked fine. Exactly the same.
I have 2 domains. On one domain I send an ajax post to the other and expect some results.
There's your problem. This is because of the Same Origin Policy in JavaScript. And thats why...
...on another domain the ajax script worked fine.
There are some workarounds though, called Cross Domain Ajax.
For your needs, since you apparently want HTML and not JSON, I would suggest a small PHP script to get the content from the other domain and forward it to your client side. This would be called Ajax proxy.
See this question
I don't see your http_request.responseText, it returns what is echo'ed in the request URL.
So try add this:
http_request.onreadystatechange = function () {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert("An error occurred: "+ http_request.statusText);
}
}
};
Before:
//parameters is a global variable with the post data.
See if it works.
Related
I am a bit forgetful of PHP, is there a simpler way to post a form using JavaScript AJAX, don't want to add jQuery simply to post an ajax request, without having to pass the parameters?
I want to post the form via Ajax and not have to get the parameters and send them in the call, is this possible? Is there an alternative to the following code...
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
var parameters="name="+namevalue+"&age="+agevalue
mypostrequest.open("POST", "basicform.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
**mypostrequest.send(parameters)**
It is my intent to use POST instead of GET to hide what is being sent on the URL, this feels strange and it's the same as using a GET. Or am I reading this wrong?
Just don't use jQuery if you only want some plain simple Ajax.
This will do the job just fine:
// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
// code
}
httpRequest.open('GET', url)
httpRequest.send()
All kudos go to: https://gist.github.com/liamcurry/2597326
Now we could also add some more browser support (IE6 and older: http://caniuse.com/#search=XMLHttpRequest) # all those jQuery heads: jQuery 2 dropped support for IE8 and older so no 'extra support' there.
// creates an XMLHttpRequest instance
function createXMLHttpRequestObject()
{
// xmlHttp will store the reference to the XMLHttpRequest object
var xmlHttp;
// try to instantiate the native XMLHttpRequest object
try
{
// create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE6 or older
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
}
catch(e) { }
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
All kudos go to: http://www.cristiandarie.ro/asp-ajax/Async.html
This post was sponsored by Google (a really powerfull tool, you type in stuff and it gives more stuff with answers)
This particular AJAX call is returning "\n" in front of the value returned by responseText.
It was previously not doing that and now when I test for a valid returned code with if (request.responseText == 100) it fails because it now equals "\n100".
I know I could strip off the "\n", but that would be a workaround and I would prefer to find the cause and fix it.
Here's my client-side code:
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 logDetails() {
var request,
Result = document.getElementById('Result'),
message = document.getElementById('message'),
url = 'ajax/login.user.php?',
us = document.getElementById('username').value,
pa = document.getElementById('password').value;
Result.innerHTML = 'Logging in...';
if (document.getElementById) {
request = AJAX();
}
if (request) {
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var r = request.responseText;
//var r = 100;
if (r == '100') {
Result.innerHTML = 'You are now logged in.';
window.location.href = "prebooks.php";
}
else if (r == '101' || r == '102') {
Result.innerHTML = 'Your login attempt failed.';
resetDetails();
}
else if (r == '103') {
Result.innerHTML = 'Sorry, you have no books subscription.';
}
else if (r == '999') {
Result.innerHTML = 'You have no more attempts!';
message.innerHTML = 'Please call us on (02) XXXXXXX so that we can assist you.';
} else {
alert(r);
}
}
};
}
// add my vars to url
url += "arg1="+us+"&arg2="+pa;
request.open("GET", url, true);
request.send(null);
}
Here's my server-side code:
<?= 100 ?>
Ok, I simplified it, but I've tried just echoing '100' directly and the issue remains.
UPDATE
I was mistaken that echoing '100' directly didn't solve the problem. It does. Sorry about that and thanks for pointing me in the right direction.
However, this does leave me with trying to find how the output is being polluted on the server-side.
On the server-side I have a class which handles the authentication and returns a value (100) to be echoed. This is the line:
echo $L->doLogin($pkg);
The lines relating to the return in the doLogin() method are:
$pkg[status]=100;
return $pkg[status];
And to be sure that a newline isn't leaking in some place, if I replace echo $L->doLogin($pkg); with echo 100; it works.
UPDATE 2 - SOLVED
It turns out that the problem was in an included class file which is included within the doLogin() method, which had recently been updated to include a single line-break at the top of the file, before the opening <?.
Many thanks to everyone for your input (I'd still be fumbling around in client-side code without it)!
I had the same problem and discovered (by adding dataFilter option to Ajax with an alert show the stringified JSON returned) that it was really the PHP script which was having syntax problem. PHP server was then pre-pending an HTML mini-document to signal the error. But then, when back to AJAX, as dataType was 'json', the whole returned PHP response was json parsed first, thus stripping off all the HTML prepended and leaving only newlines. These newlines in front of valid JSON returned data was causing the JSON data to be considered syntax error, and that was it ! With dataFilter option sending the raw data in an alert, I was able to see the PHP script initial error and once corrected, no more newlines pre-pended!
i had the same problem and i understood I hit Inter several times in end of page that i incloude to my page and when i delete it my responseText show without \n. :)
example:
_enter
_enter
_enter
If I have a list of elements, and via javascript the user moves the elements in another order, can I, after each move, launch a php code (like a php page) but without having to call it in the browser?
Create an XmlHttpObject for the URL, send() it, check results to see if the call was successful, and discard the responseText. As an example, suppose you have the new order in a variable testUrl, e.g., "http://domain.com/script.php?order=1,4,3,2"
var xmlHttpObject = new XMLHttpRequest();
xmlHttpObject.open("GET", testUrl, false);
xmlHttpObject.send();
var xmlText = xmlHttpObject.responseText;
if (xmlText == 'Success')
// do nothing
else
alert (xmlText);
An addition to the above answer - for the sake of posterity, in case someone has to debug your code some day :) I use the following function call to get that object: (I believe it makes the JS more readable and portable). You can check the return value and if null, alert the user that AJAX is not supported by the browser.
function getXmlHttpObject () {
var xmlHttpObject = null;
try {
xmlHttpObject = new XMLHttpRequest();
} catch (ex) {
try {
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
} catch (ex) {
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xmlHttpObject;
}
I think I'm getting ahead of myself, but I tried AJAX tutorials to read from a PHP file. The PHP file simply has an echo statement for the time, and I want to pass that to initialize a javascript clock.
But this is my first time trying AJAX and I can't even seem to get it to activate a test alert message.
Here is the code, it's at the bottom of my PHP page after all of the PHP.
<script type='text/javascript'>
function CheckForChange(){
//alert("4 and 4");
//if (4 == 1){
//setInterval("alert('Yup, it is 1')", 5000);
//alert('Now it is changed');
//}
var ajaxReady = new XMLHttpRequest();
ajaxReady.onreadystatechange = function(){
if (ajaxReady.readystate == 4){
//Get the data
//document.getElementById('clocktxt').innerHTML = ajaxReady.responseText;
alert("here");
alert(ajaxReady.responseText);
}
}
ajaxReady.open("GET","ServerTime.php",true);
ajaxReady.send(null);
}
setInterval("CheckForChange()", 7000);
</script>
Can somebody tell me why this isn't working? No idea what I'm doing wrong.
The problem in your code is an uncapitalized letter. (Oops!) You check ajaxReady.readystate; you need to check ajaxReady.readyState.
Because ajaxReady.readystate will always be undefined, your alerts never fire.
Here's your code fixed and working.
As an aside, have you considered using a library to handle the ugliness of cross-browser XHR? jQuery is your friend:
function CheckForChange(){
$.get('ServerTime.php', function(data) {
$('#clocktxt').text(data);
});
}
You should probably have something like:
setInterval(CheckForChange, 7000);
On an unrelated note, it's common naming convension in JavaScript to have function and methods names' first letters not capitalized, and the rest is in camelCase. i.e. checkForChange().
I'm not sure the exact problem with your code; here's what I use -- I'm sure it will work for you. (plus, it works with more browsers)
var xhr = false;
function CheckForChange(){
/* Create xhr, which is the making of the object to request an external file */
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
/* End creating xhr */
/* Retrieve external file, and go to a function once its loading state has changed. */
if(xhr){
xhr.onreadystatechange = showContents;
xhr.open("GET", "ServerTime.php", true);
xhr.send(null);
}else{
//XMLHTTPRequest was never created. Can create an alert box if wanted.
}
/* End retrieve external file. */
}
function showContents(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText);
}else{
//Error. Can create an alert box if wanted.
}
}
}
setInterval(CheckForChange, 7000);
In a Form, I am calling a PHP file if the validation passes. My Form header looks like this:
<form method="POST" action="inst.php" style="margin:0px;"name="form1" onSubmit="return CheckUsername(document.getElementById('username').value);">
</form>
The problem is that even if the validation fails, it shows a blank page in an attempt to open the PHP file, when it must remain on the same page. The PHP file contains code to access the database to check whether the user exists or not.
Is there any way to check the database for value without refreshing the page?
It is very likely that the JavaScript function has an error. The validation function will then not be executed and the form sent (!). Check Firefox's Javascript console for errors, they will appear there even if the page has already reloaded.
You should however never rely on client side validation. I would highly recommend checking in the PHP script as well.
While you should never rely upon client-side verification alone and should definitely treat all data as "dirty" in the PHP, there is another way using JavaScipt that you can prevent the browser from directly posting the form. Rather than setting the form's method and action, simply define its onsubmit function to construct an XmlHttpResponse object, set the method to POST and set data to your form.serialize(), and send the appropriate POST request. Or, if the PHP script will accept GET or REQUEST parameters, you can (after your verification) construct the URL query and simply set window.location to redirect to the PHP page with the appropriate data.
EDIT - Here is my illustration - this uses Prototype's Form.serialize function.
<form id="my_form" onSubmit="return checkUsername();">
Username: <input type="text" name="username" id="username" />
</form>
<script type="text/javascript">
var xhr; // global XMLHttpRequest object
var formElem = $('my_form'); // our form element
function checkUsername() {
var formData = formElem.serialize();
sendPOSTRequest('http://mydomain.com/mypath/myscript.php', formData);
}
function sendPOSTRequest(toURL, sendData) {
xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xhr) {
alert('Cannot create XHR');
return false;
}
xhr.onreadystatechange = handleResponse;
xhr.open('POST', toURL, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", sendData.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(sendData);
}
function handleResponse() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = xhr.responseText;
// result is now whatever content was returned by the PHP script
// do whatever you want with the result here
// for example, you might have the PHP return 'true' or some such thing, and then
// change window.location, or perhaps if it returns 'false' you put up an alert('No!')
// use your imagination, go nuts
} else {
alert('The script returned an error.');
}
}
}
</script>
There are some more sophisticated ways to create and handle the XMLHttpRequest object. I might post an update later with some pointers.
Once the POST request has been sent then it is up to the browser how it handles the response, but in every browser I have come across it will display the result of the request in some for be it a message saying it recieved a response (200,404, etc), a blank page or whatever, so I'm afraid you will have to reconstruct your page and send it back to the client (complete with invalid entries in the form elements) as a response.
Its a pain, but that's how HTTP works.