JSONRequest.post not functioning - javascript

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

Related

How to send correctly FormData with XMLHttpRequest and simple JavaScript?

This is the form:
<form id="login_form">
Login<br/>
user: <input id="login_user" name="login_user" type="text" /><br/>
pass: <input id="login_pass" name="login_pass" type="password" /><br/>
<input type="button" value="Submit" onclick="doStuff("login")" />
</form>
this is the js I used:
function doStuff(doWhat){
var sendString = new FormData(document.getElementById("login_form"));
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "?action="+doWhat, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
//do stuff
}
};
xmlhttp.send(sendString);
}
The PHP page only has echo var_dump($_POST);
If I send it like that it returns this, that I have no idea how to use:
D:\wamp64\www\test\index.php:18:
array (size=1)
'------WebKitFormBoundaryubX9lqZJrSEuJwB9
Content-Disposition:_form-data;_name' => string '"login_user"
admin
------WebKitFormBoundaryubX9lqZJrSEuJwB9
Content-Disposition: form-data; name="login_pass"
swordfish
------WebKitFormBoundaryubX9lqZJrSEuJwB9--
' (length=173)
If I try anything else, like using JSON.stringify() on the FormData before sending it or changing the content type from application/x-www-form-urlencoded to multipart/form-data it just returns an empty array. I should not use jQuery for this. Is there a way to send something usable or make the PHP page able to read it?

Problems with XMLHttpRequest and PHP

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!

Submit multiple values of a form using AJAX (but no jQuery) - XMLHttpRequest

Normally I'd use jQuery for this, but to cut a long story short, on this I can't.
I've successfully submitted a form via AJAX which has only one element of a form, like this:
<div id="response"></div>
<form onsubmit="submitStuff(this.datatosend.value);this.reset();return false;">
<input id="datatosend" type="text" />
<input type="submit" />
</form>
<script>
function submitStuff(e) {
if (e == "") {
document.getElementById("response").innerHTML = "";
return
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText
}
};
xmlhttp.open("GET", "sumbitData.php?data=" + e, true);
xmlhttp.send()
}
</script>
Now say I have this form:
<form onsubmit="????????????????????;this.reset();return false;">
<input id="datatosend1" type="text" />
<input id="datatosend2" type="text" />
<input type="submit" />
</form>
How do I do the same, submitting both values?
I'm a bit new to Javascript, especially 'pure' Javascript so please be a bit patient!
Build up the string
var data1 = encodeURIComponent(document.getElementById("datatosend1").value);
var data2 = encodeURIComponent(document.getElementById("datatosend2").value);
var url = "sumbitData.php?data1=" + data1 + "&data2=" + data2;
Read the form values and make a string to attach to the url:
var child=document.getElementById(form_id).getElementsByTagName('input');
var data=new Array();
for(var i=0;i<child.length;i++){
data.push(child[i].id + '='+ encodeURIComponent(child[i].value));
}
data='?' + data.join('&');

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?

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