submit a form with ajax and js - javascript

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

Related

How to pass input values to ajax

Okay, I'm new to Ajax. My problem is that I'm not sure how to retrieve data which is in the <input> tag and send it to Ajax. I have tried searching on the internet, but most of the solutions are using jQuery Ajax, which is what I'm not looking for at the moment.
Here is my code.
I want to save this value so that my Ajax can read it...
<input id="IDValue" name="IDValue" value="<?php echo $row['exist']?>" >
This is my Ajax script...
function message(){
var ID=$(".IDValue").val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","retrieveMsg.php?q=" +ID,true);
xmlhttp.send();
}
Please help me, guys. The reason I am doing this method is because (My previous post) Send input value to php using ajax with result printed to div
Replace it
var ID=$(".IDValue").val();
With
var ID = document.getElementById("IDValie").value;
i am confused about your $row['exist'] returns value or not and what html control you used for id="txtHint". here i have provided demo which same as your code in some way...try and have an idea and make changes as per your requirement...
<html>
<head>
<script src="jquery.js"></script>
</head>
<body>
<input id="IDValue" name="IDValue" value="<?php echo 'hello';?>" >
<textarea id="txtHint"></textarea>
<input type="button" value="Click" onClick="message()"/>
<script>
function message(){
var ID=$("#IDValue").val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","login.php?q=" +ID,true);
xmlhttp.send();
}
</script>
</body>
</html>

Ajax Post to PHP and Get Return Data

I am developing a slider to set my budget and would like to achieve the value which I set in slider1.php. However, when I tried using the code below, I encountered an error
"Notice: Undefined index: slideStatus in C:\xampp\htdocs\1204763e\slider1\slider1.php on line 4
Thank you , says the PHP file"
In slide.php, I inserted this set of code:
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(val){
var hr = new XMLHttpRequest();
var url = "slider1.php";
var ss = document.getElementById('sliderStatus').innerHTML = val;
var vars = "sliderStatus="+ss;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<input type="range" name="slide" min="0" max="100" value="50" step="2" onChange="ajax_post(this.value)" />
<br /><br />
<span id="sliderStatus">50</span>
<br/><br/>
<div id="status"></div>
</body>
</html>
In slider1.php, I inserted this set of code:
<?php
echo 'Thank you '. $_GET['slideStatus'] . ', says the PHP file';
?>
You seem to try to access "slideStatus" but you are posting "sliderStatus".

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;"

Ajax Not Loading Asynchronous. Refreshing Page when form submitted

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?

JSONRequest.post not functioning

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;">

Categories