XML HTTP GET Request Fails - javascript

I'm doing a pure JS GET request, to my localhost (don't worry I tested POST and that works), I can access all the database and everything else but the GET request won't work. My JS code is shown below:
functtion getSessionKey() {
XMLHTTP = new XMLHttpRequest();
XMLHTTP.open("GET", "http://127.0.0.1:8080/projects/To-Do-App/api/sessionData/sessionKey.php", true);
XMLHTTP.onreadystatechange = function () {
if (XMLHTTP.readyState == 4) {
alert(XMLHTTP.responseText);
}
}
XMLHTTP.send(null);
}
In the PHP file I have the following code:
<?php
session_start();
if (isset($_SESSION['sessionKey']) && !empty(trim($_SESSION['sessionKey']))) {
echo htmlspecialchars(trim($_SESSION['sessionKey']));
}
?>
The POST requests all work and insert into the database, but the GET request seem to stop all the JS code below it from working. Any ideas why? I have tried changing the last parameter true/false. Also I am trying to make it for a mobile application through Intel XDK so I using JS and PHP if that helps. Please no jQuery solutions as that doesn't seem to work.

You didn't set the content type
var XMLHTTP = new XMLHttpRequest();
XMLHTTP.setRequestHeader("Content-type","application/x-www-form-urlencoded");
...
and try to replace
XMLHTTP.send(null);
with
XMLHTTP.send();

Don't send a null in with the .send() Make it
XMLHttp.send()

Related

Link triggering XMLHttpRequest

I have made a simple XMLHttpRequest which does work, it sends request etc. Just like in W3 schools.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demox").innerHTML = this.responseText;
}
};
xhttp.open("POST", "textx.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=" + textxx);
}
The problem starts when I try to trigger the request by clicking a link, which sends me to the php file which processes the request. I find it hard to understand on my current level why it doesn't work, since it worked with simple forms and such.
I get:
"Notice: Undefined index: fname ..."
So, I assume, it means the variable wasn't sent. Can someone explain? Or is there way to debug the things that are being sent from one page to another. All I found was a debugger in chrome which indeed captures the requests, but has no real use, since I get sent to the textx.php page and all is lost.
Not really sure, where your problem might be, maybe try:
var xhttp = new XMLHttpRequest();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.open("POST", "textx.php", true);
xhttp.onreadystatechange = function() {
if (this.readyState === 4){
if(this.status===200 || this.status===0){
document.getElementById("demox").innerHTML = this.responseText;
}
};
var fname = "fname=" + textxx;
xhttp.send(fname);
}
You might console.log(xhttp); and see the step by step profile and find out where the problem might be.
Either way, I am still not sure, but I uploaded my page(code) to a hosting server and the code worked. PHP didn't show any warnings and all went as planned. The problem it seems has to do something with running a local server(WAMP). Changing PHP version didn't help. I may need to dig a little deeper on this.

Call PHP function by name from JavaScript

I have a javascript function that's executed on a button click and I have an included file containing all my PHP functions. One of the PHP functions returns me an array of filenames encoded as a JSON object. I'd like to call this function from my Javascript function so that I can use the array. I know I can call a PHP file which would run but in this case I only want to call one specific named method.
I tried the following but couldn't get it to work (Console error: Unexpected < )
function getPHPArray(){
var picArray;
picArray = <?php getPicArrayJson(); ?>;
}
Can this be done using XMLHttpRequest or do I need to find another method? (If reasonably possible I'd prefer straight Javascript over JQuery but I can use JQuery if it makes this significantly easier)
If so how?
My PHP method is as follows:
function getPicArrayJson(){
global $fileArrayString;
If (!empty($fileArrayString)){
echo json_encode($fileArrayString);
}
}
My JavaScript so far:
function getPHPArray(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "phpFunctions.php?name=getPicArrayJson", true);
xmlhttp.send();
}
This is essentially a Remote Procedure Call. For use with PHP, I'd check out JSON-RPC PHP.
Anyway, here's a basic way you can do it without much complexity to your app. You will have to make an ajax request to the server. The idea for you here is to use call_user_func.
call_user_func("getPicArrayJson");
You can use
call_user_func($_POST["name"]);
But I highly recommend that you only allow certain functions to be called
phpFunctions.php
$allowed_functions = array("getPicArrayJson");
$name = $_POST["name"];
function getPicArrayJson() {
$pics = array("1.jpg", "2.jpg");
return json_encode($pics);
}
// legal function
if (in_array($name, $allowed_functions)) {
header("Content-Type: application/json");
$json = call_user_func($name);
die($json);
}
// invalid access
else {
// Error 400
}
Then do you Ajax request per normal
...
xmlhttp.open("POST", "phpFunctions.php?name=getPicArrayJson", true);
xmlhttp.send();
ps my own two cents, I would use a GET request for this. Following RESTful API conventions for web services, a POST request would only be used to create a new element.

Execute <script> from separate .php file

Been working on (what seemed like) a simple issues for a few days now and could use some help.
I call a php file on a button-click, do a bunch of server-side operations, and wish to change a few things in the HTML at the end of the php (change images, changing text, enabling buttons, etc.)
So, what I'm trying to do (for the test case here) is change an image twice. It works fine in the first set of code (script in the html file), but it doesn't work in the second set of code (script in the php file). I.e., I see oldImage when the page loads, secondImage when I click the button, but I never see newImage.
<button onclick="test()">Try The Test</button>
<img id="myImage" src="oldImage.jpg">
<script>
function test()
{
var img = document.getElementById('myImage');
img.src = 'secondImage.jpg';
xmlhttp=new XMLHttpRequest();
xmlhttp.open("testPhp.php",true);
xmlhttp.send();
}
</script>
Here's myPhp.php (all on one line in my code; two lines here, for readability):
$script = "<script> var img = document.getElementById('myImage');
img.src = 'newImage.jpg'; </script?";
echo $script;
Any ideas on why the script in myPhp.php doesn't work?
EDIT:
I changed the HTML portion to this, then changed myPhp.php to echo "Hello World", which shows up just fine within myDiv. However, I can't seem to echo the script. Is there any way to do this?
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","portTester.php",true);
xmlhttp.send();
If your ajax call returns markup, for it to have any effect, it has to be added to the DOM.
But I wouldn't recommend doing it this way. Instead, have your PHP file return the information (not a script), and then have the code receiving the information (in the onreadystatechange handler of the XHR object) read that information and take the relevant action.
For example, your PHP could simply return:
newImage.jpg
Then your ajax call would be:
function test()
{
var img = document.getElementById('myImage');
img.src = 'secondImage.jpg';
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = handleReadyStateChange;
xmlhttp.open("testPhp.php",true);
xmlhttp.send();
function handleReadyStateChange() {
if (xmlhttp.readyState === 4 && xmlhttp.status >= 200 && xmlhttp.status < 400) {
// Request is complete and successful
img.src = xmlhttp.responseText;
}
}
}
If you need to send back richer information (as is frequently the case), look at using JSON.
You're not doing anything with the response to your AJAX call. In other words: You are calling the PHP script, the reply is printed, but is thrown away, because your Javascript isn't doing anything with it. You must add some code to interact with the reply. Here's a hint: Don't try to output Javascript from PHP, output something that you USE in your Javascript.
Add this to your Javascript after the xmlhttp.send() call:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myImage").src = xmlhttp.responseText;
}
}
And in your PHP script, put just this:
echo 'newImage.jpg';
One possible issue is that you are missing the semi-colon after your test() in the onclick. Also, your </script> tag is malformed; it reads </script? while it should read </script>. Also, where into the DOM is this echoing? It should go into the head of your document. Right now, it looked unspecified.

XMLHttpRequest status 0 on second load

I am experiencing an interesting issue when I am trying to load some data in .txt format from the same domain using XMLHttpRequest.
I am trying to load the data, parse it and then store it in localStorage
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var temp;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
temp = xmlhttp.responseText;
}else{
alert("readyState: " + xmlhttp.readyState + "status: " + xmlhttp.status);
}
}
xmlhttp.open("GET","data/somedata.txt", false);
xmlhttp.send();
This code only works if I clean the history and cache; however, on second click of the same link, I would received "Readystate: 4, status 0" for some reason.
Does this has anything to do with localStorage?
if (!localStorage.somedata || localStorage.somedata.count(':') !== somedata.count(':')) {
localStorage.somedata = temp;
}
window.somedata = JSON.parse(localStorage.somedata);
There are two causes of status code of zero.
Making calls from the file protocol.
The page is refreshing/navigating away as the request is being made.
In your case I would assume it is #2. If you are using a button or a link to make the Ajax call, make sure to cancel the click action with either preventDefault or return false.
Sounds like a caching issue. Try either switching to a POST method, or appending a timestamp to the GET request querystring and see if that prevents the caching.
xmlhttp.open("POST", "data/somedata.txt", false);
or:
xmlhttp.open("GET", "data/somedata.txt?" + new Date().valueOf(), false);
Edit: If those don't work, modify your server configuration to send appropriate response headers for that file or type to not cache the response. Ie: Cache-Control: no-cache
Try xmlhttp.abort() before opening a new request.
It's a long shot but worth the try.

XMLHTTPrequest request not working

I tried the following code to send request to jsp page on a click of button. I checked on Httpfox but no request is going. I just used the whole of this code in the body of the html code. Am I doing some silly mistake. Kindly suggest..
<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
// Do something with the text here
alert(substring);
}
}
xmlhttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
</script>
Well, in JavaScript, variables are case-sensitive. You have xmlHttp and xmlhttp; those should be the same.
You've also got <pre><code> at the beginning of your <script> block, which is a JavaScript syntax error.
Since no request is being made, I am not convinced you can actually make requests to "http://csce:8080" as FireFox may not see that URL as being on the same subdomain (You cannot make Ajax requests for resources not on the same domain as the requestor).
Suppose you made the URL relative. Is a request even generated then? If so, that is likely your problem.
Quote: xmlhttp = new XMLHttpRequest();
Two things. First, you might want to use a more robust method of getting an XMLHttpRequest object. Second, javascript is case-sensitive; xmlhttp != xmlHttp
xmlHttp = (function (x,y,i) {
if (x) return new x();
for (i=0; i<y.length; y++) try {
return new ActiveXObject(y[i]);
} catch (e) {}
})(
window.XMLHttpRequest,
['Msxml2.XMLHTTP','Microsoft.XMLHTTP']
);
Quote: http://csce:8080/test/ind...
Keep in mind that cross-domain xmlhttp is verboten. Unless you're serving from csce:8080, that ain't gonna work.

Categories

Resources