Trying to get an image url from AJAX, getting status = 0 - javascript

I have an input, say "xxx".
the server returns an image in GET method in: https://website.com/xxx
All I want is for the image that returns when going to that url to be displayed.
Wrote a little script for it but i always get status = 0. I wonder why it is and how can it be 200.
<!-- templates/homeDEV.html -->
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<form method="GET">
<p>AJAX Address: <input id="address" type="text" name="address" maxlength="64" size="64"></p>
<p><input type="submit" value="Generate AJAX" onclick="loadImage()"/></p>
</form>
<script>
function showImage(src) {
var img = document.createElement("img");
img.src = src;
document.body.appendChild(img);
}
function loadImage() {
var theReturn = document.getElementById('address').value;
var url = "https://monkey-g.herokuapp.com/monkey/" + theReturn;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
showImage(url);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
</script>
</body>
</html>

You are running your JavaScript when you click the submit button in a form.
This:
Initiates the Ajax request
Submits the form
Leaves the page
Cancels the Ajax request (because there is no longer any JS to handle the response)
Loads the new page
Remove the form, and make the button a JS (type="button") button.

You don't need to AJAX an image. There's not possible way to stuff an Image from an AJAX request into an image tag. The image tag itself is all you need.
Also, as Quentin said, your page is going to refresh before your ajax call is made anyway if you use a form.
function loadImage() {
var theReturn = document.getElementById('address').value;
var url = "http://monkey-g.herokuapp.com/monkey/" + theReturn;
var img = new Image();
img.src = url;
document.body.appendChild(img);
}
<p>AJAX Address: <input id="address" type="text" name="address" maxlength="64" size="64">
<p><input type="button" value="Generate AJAX" onclick="loadImage()" /></p>

Related

Safari not sending AJAX form data

A strange problem has started on a page where the code hasn't been changed. I have stripped things back and have now isolated the issue, but I can't make sense of it.
On this form if I only input the text field, Safari wont send the form (although no errors occur). It does send in Firefox when only the text field is entered.
Safari will send the form if the image field has a file or if I remove the image filed altogether. So for some reason the lack of data in the image field is causing the form to not send in Safari.
It seems to matter that the text field is created by Javascript, if I just make the page with a regular text input to start with the problem doesn't occur.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" language="javascript">
function sendForm(){
var formElement = document.querySelector("#upload");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "test.php");
request.send(formData);
}
</script>
</head>
<body>
<form name="upload" id="upload" >
<h2>Image</h2>
<input name="image" type="file" />
<p onclick="sendForm()" />SEND</p>
</form>
<script>
for (var f = 0; f < document.forms.length; f++) {
new_input = document.createElement('input');
new_input.type = 'hidden';
new_input.name = 'title';
new_input.value = 'test';
document.forms[f].appendChild(new_input);
}
</script>
</body>
</html>
I am tracking the data sent with:
<?php
$title = $_REQUEST['title'];
$file = 'output.txt';
$current = file_get_contents($file);
file_put_contents($file, $title."\n");
?>
Additionally if request.send(formData); is changed to request.send("test"); then "test" will be sent in all cases, so it appears Safari is having an issue with the FormData object.
I have aso tested this using the fetch() API and the same thing happens.

function works but don't alert and reload

I wrote a small form to log-in into my website :
<form id="log_form" onsubmit='return loginjs()' method="post">
<input type='text' placeholder="login" size='30' name='login' class='test'/>
<input type='password' placeholder="password" name='password' size='30'/>
<input type='submit' value='Connect' id='signin' />
</form>
and I wrote this Javascript function to send the form's data to a php page which going to check if everything is ok and make the session up.
function loginjs() {
'use strict';
var form = document.getElementById('log_form');
var btn = document.getElementById('signin');
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
if (request.responseText != 'ok')
alert(request.responseText);
}
}
}
var post = "login=" + form.login.value + "&password=" + form.password.value;
request.open('POST', 'functions/func_login.php');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(post);
location.reload();
};
My function is perfectly called each time I press ENTER or click on Submit, but sometimes the alert doesn't show up and the location.reload(); aren't called.
I don't have any error in my console... and if I manually reload the page, i'm logged so my ajax was sent.
I'm looking for 2 days to find the bug, and doesn't succeed to find. Could someone help me?
I can't use jQuery or another library I've to use JS Vanilla :)
Thank you
Try moving the location.reload(); code in the success block of the ajax, i.e. reload the page after the ajax response is received (if no error is received).

Unable to receive something in PHP from XMLHttpRequest's "POST"

First off, here's my code:
HTML ("formdata-index-test.html"):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test page</title>
</head>
<body>
<form id="the-form" method="post" action="formdata-validation-test.php">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
<script src="formdata-fields-control-test.js" type="text/javascript"></script>
</body>
</html>
JS ("formdata-fields-control-test.js"):
var form = document.getElementById("the-form");
form.onsubmit = function() {
var q = document.getElementById("the-text").value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send("q="+q);
}
PHP ("formdata-validation-test.php"):
<?php
$example = $_POST['q'];
echo $example;
if (empty($example)) {
echo "Empty";
}
?>
Now, at the beginning, I wasn't getting anything as response, but after a few tries and changes in my code, I'm being able to receive that alert in the JS file. The weird thing is that, even receiving the alert, I'm still getting the "Empty" echo when the PHP page is loaded after the form submission. Does anyone know why is it happening? My final goal is just to send the text from the HTML file to the PHP file, and then to database (that is, the "responseText" is not really necessary, and it's here just with test purposes), but apparently, PHP is not really receiving what JS sends, while JS receives what PHP sends. Does it make any sense?
The submit button is clicked and a submit event fires on the form.
The JavaScript is running. It is making an HTTP request to the PHP script with the data in it. Since you have forced it to be a synchronous request (don't do that, it locks up the event loop), the browser waits for the response before continuing. The JS is then processing the response, and alerting the value.
Then the form is submitted. It doesn't have a control with name="q", so for the second request to the PHP script, empty($example) will always be true.
If you want to stop the form being submitted then call preventDefault on the event object.
form.onsubmit = function(event) {
event.preventDefault();
try this :
1) in formdata-fields-control-test.js , make your script as a function :
function testFunction() {
var q = document.getElementById("the-text").value;
var params = "q="+q;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ((xhr.readyState == 4) && (xhr.status == 200)) {
alert(xhr.responseText);
}
}
xhr.open("POST", "formdata-validation-test.php", false);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(params);
};
2) in formdata-index-test.html , set action to empty and call the javascript function onsubmit :
<form id="the-form" onsubmit="return testFunction()" method="post" action="">
<input type="text" id="the-text">
<input type="submit" value="Upload">
</form>
the issue i think was with the form having an action and a onsubmit function together.

Ajax acting as GET method even though is POST method

Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"

submit a form with ajax and js

so i tried to "parse" the form object with js and pass stuff that was supposed to be used to URL and submit a form with ajax.the code did not work.both A and B parameters were not successfully passed to server and response as i thought at the first place.
<html>
<head>
<script type="text/javascript">
function ajaxForm(form){
form = document.getElementById(form);
var elements = form.elements;
var content="";
var element;
for(i=0;i<elements.length;i++){
element = elements[i];
if(element.type=="text"){
content += encodeURIComponent(element.name)+"="+encodeURIComponent(element.value)+"&";
}
}
ajaxSubmit(content);
}
function ajaxSubmit(content){
if(content.length==0){
document.getElementById("txtinput").innerHTML="";
}
if(windows.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtinput").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","process.php?"+content,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="ajax_form">
A:<input type="text" name="A" />
<br/>
B:<input type="text" name="B" />
<input type="submit" onsubmit="ajaxForm('ajax_form')" />
</form>
<p>Elevator:<span id="txtinput" ></span><br/></p>
</body>
</html>
process.php:
<?php
$response = "This is simply an example for debugging purposes";
echo $response;
?>
AjaxForm and AjaxSubmit are never getting called, instead the form is getting submitted in the normal way. You need something like
<form id="ajax_form" onsubmit="ajaxForm('ajax_form');return false;">
try changing encodeURLComponent to ecodeURIComponent

Categories