I have been trying to learn ajax and from what I can see my code is correct however it always refreshes the page when it echo's the returned json string. Any help would be greatly appreciated!
<script>
// Get XML HTTP Type
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxSuccess () {
alert(this.responseText);
}
function ajaxrequest(oFormElement) {
//Get The Correct XMLHTTP Object
var request = new XMLHttpRequest();
request.open(oFormElement.method, oFormElement.action, true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(new FormData(oFormElement));
return false;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
alert("done");
document.getElementById('comment_form').innerHTML = request.responseText;
}
}
}
</script>
<form action="<?php echo $add_comment; ?>" method="post" enctype="multipart/form-data" id="comment_form" onsubmit="ajaxrequest(this);">
<input name="user_id" type="hidden" value="<?php echo $user_id; ?>">
<input name="user_message_id" type="hidden" value="<?php echo $user_message_id; ?>">
<textarea id="new_comment" name="new_comment" cols="100" rows="5"></textarea>
<input type="submit" value="post request"/>
</form>
You have to stop the event from happening. there is a common used function this in javascript:
e.preventDefault; // e is the event that you need to pass to your function.
or Change <input type="submit" value="post request"/>
to
<input type="button" onclick="ajaxrequest(this);" value="post request"/>
what is going to happen is your form is only going to be processed by javascript and page will mot reload due to the form submission.
Just modify this approach for yourself and it should fix your issue.
Use Jquery library http://api.jquery.com/jQuery.ajax/, but if u wanna build your own script. consult w3c documentation http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
As Pointy pointed out, you might want to prevent the default click event of the submit button from firing
submitForm( event ) {
event.preventDefault();
}
http://api.jquery.com/event.preventDefault/ <- My bad...
Just for clarification, is that your complete code?
Related
I've been following along a tutorial, but I just can't make it to work. One hour of trying to figure it out, but nothing. This AJAX request returns nothing. I'm a beginner. Help is appreciated.
<form id="postForm">
<input type="text" name="name" id="name1">
<input type="submit" value="submit">
</form>
<script type="text/javascript">
document.querySelector('#postForm').addEventListener('submit', loadText5)
function loadText5(e) {
e.preventDefault();
let name = document.getElementById('name1').value;
let params = "name"+name;
let response = new XMLHttpRequest();
response.open('POST', 'process.php', true);
response.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
response.onload = function() {
console.log(this.responseText);
}
response.send(params);
}
</script>
Process.php
if (isset($_POST['name'])) {
return 'POST: Your name is ' . $_POST['name'];
}
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;"
I'm fairly new to both JavaScript and PHP, so I hope this problem isn't as complex as it seems to me. I'm trying to send data from a form to a PHP file using XMLHttpRequest, and then display the output of the PHP as an alert. Here's the HTML and JavaScript:
<form onSubmit="password_Check()">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function password_Check() {
var url = "test.php";
var pass = $("#pass").val();
var xhr = new XMLHttpRequest();
xhr.open("GET", url+"?pass="+pass, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
}
</script>
And here's the PHP:
<?php
$pass = $_GET["pass"];
echo "The password is $pass! We've done it!";
?>
I've tried all sorts of ways to do this, like $.post, $.get, $.ajax, and an xhr using POST. But I can't seem to get this to work. Now it just appends "?password=(whatever I put)" onto the end of the current url, which does nothing, but it shows it's doing something.
In your code you are missing the send part where you actually trigger the request. If you are not triggering the request then there is no point of the event listeners which listen for the state changes.
do it like
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send();
Also in your question you are mentioning about jquery ajax, with $.get your code could be as simple as
$("#form1").on("submit",function(e){
e.preventDefault();
var url = "test.php?pass=" + $("#pass").val();
$.get(url,function(data){
//handle data here
});
});
You forgot to execute the request. xhr.send():
Also note that since you're having an XMLHTTPRequest, you need to prevent the default behavior (which is the form is going to be submitted) by using .preventDefault();
<form id="form1">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
// handle the submission event
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault(); // prevent from submitting
var url = "test.php";
var pass = document.getElementById('pass').value; // be faithful!, just use plain javascript
var xhr = new XMLHttpRequest();
var params = '?pass='+pass;
xhr.open("GET", url+params, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(); // send it
});
</script>
If you are using jQuery then better use jQuery's ajax functions instead of xhr by yourself!
Also if you are submitting the password, better not submit it using GET request as it will be visible in the URL. Instead always use POST when handling Passwords!
Client side:
<form action="/index.php" id="myform" method="post">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
$('#myform').on('submit', function() {
$.ajax({
type: $(this).attr('method'), //Taking for the form attribute
url: $(this).attr('action'),
data: $(this).serialize(), //Takes care of all input fields in the form! No need to pass one by one!
success: function(response) {
if(response == 'success') {
window.location.href = '/url-to-goto'; //Set your redirect url here
}
else {
//Handle invalid password here
alert(response);
}
}
});
return false;
});
</script>
Server side:
<?php
//If you are handling password, better to put it in the post body instead of url for security reasons
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//Check password here
if(isset($_POST['password']) && $_POST['password'] == '123') {
die('success'); //successful! redirect user!
}
die('Invalid password!');
}
?>
Hope that helps you better understand!
I am developing a web page and the purpose is to perform an http POST from form input elements, in JSON format. While the JSON element to be sent is formed properly, the request is never performed. Here is the code I have been using.
Form
<form id="input" action="javascript:snifForm()" >
User ID:
<input type="text" name="userId" id="userId" required>
Name:
<input type="text" name="name" id="name" required>
<div class="form-submit"><input type="submit" value="Submit" color="#ffffff" > </div></p>
</form>
Javascript (JSON.js, JSONRequest.js and JSONRequestError.js are imported)
<script type="text/javascript">
var requestNumber;
function snifForm()
{
var a1=document.getElementById("userId").value;
var a2=document.getElementById("name").value;
var toSend= {interactions: {id_user:a1, id_name:a2}};
var jToSend=JSON.stringify(toSend);
requestNumber = JSONRequest.post(
"http://someurl.com",
jToSend,
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
alert(value);
} else {
processError(exception);
}
}
);
alert(requestNumber);
}
</script>
I also tried the more classic form:
var xmlhttp = new XMLHttpRequest();
var out;
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
out = xmlhttp.responseText;
alert(out);
}
else alert('nothing');
}
xmlhttp.open("POST", "the_same_url", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(jToSend);
After checking the server logs, no post is done ever :/
You should be attaching the event to the submit action of the form and you need to make sure to cancel the submit action.
I would not add the events directly to the form, but it is
<form id="input" onsubmit="snifForm(); return false;">
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