POST to web service on page load - javascript

I'm trying to send some data to a web service on page load and then allow the page to continue to work as usual. The idea is to grab some data from the client just when the page loads without user interaction and then let the user continue with the page normally.
I'm using XMLHttpRequest, when I wanted to do the POST to the web service without refreshing the page, I don't know if that's the best method. Here is my current test html:
<html>
<body>
<form name="myform2" method="post" action="./login.asp">
First Name: <input type="text" name="fname" /><br><br>
Last Name : <input type="text" name="lname" />
<input type="submit" value="Submit" />
</form>
<form action="" id="myform">
<input type="submit" value="send-info"/>
</form>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function() {
$(document).on('submit', '#myform', function() {
var http = new XMLHttpRequest();
var params = ("myvar=somedata");
http.open("POST", "http://127.0.0.1:3000", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
return false;
});
});
</script>
</body>
</html>
Right now the data is sent when I click the send-info button but I need to send it without user interaction, without refreshing the page and allowing whatever additional logic is needed after that. I have tried with window.onload without success.
Please excuse my poor programming skills, I'm not that versed on Javascript.

You should just be able to remove the "on submit" so your code runs when the "document ready" event is called. Also if you are using jquery you can use its ajax function to simplify the http call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://127.0.0.1:3000",
data: { "myvar" : "somedata" }
});
});

Right now you are sending data on submit form. So you need to use ajax call right after your $(document).ready(function() Here is a sample
$(document).ready(function()({
myvar = somedata;
$.ajax({
url: "test.html",
type: "Post",
data: {myvar : myvar},
success: function(response){
//do anything here
}
});
});

Related

jQuery Ajax loop on form submit

New to Ajax, however, I can't figure out what is wrong, and I assume its the Javascript. My php page is working just fine, however, with this code my login Html simply refreshes over and over with the end of the url changing to ?username=whatIenter&password=whatIenter
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('#login_form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/lib/login.php',
data: $(this).serialize(),
success: function(data)
{
alert("WORKED");
}
});
});
});
</script>
HTML
<form id="login_form" action="" method="POST">
<input type="text" id="user" name="username">
<input type="password" id="pass" name="password">
<button id="loginButton" class="login_submit" type="submit" >Login</button>
</form>
First of all, which jQuery version are you using?
Your code is working fine with jQuery 3.3.1
Always keep in mind this good practices:
Disable the cache on your browser while you develop
Each time you wanna check your site, open the browser console and then press F5
Javascript code always needs to stay at bottom inside body tag (just before </body>)
This also apply in the case you put it on a separated file (recommended)
Set the action parameter on your form, this can prevent unexpected errors
Even if you are gonna call the same file or url
Try:
var header = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
};
var request = $.ajax({
url: '/lib/login.php'
,data: $(this).serialize(),
,headers: header
});
request.done(function(response) {
alert("WORKED "+response);
});
The thing is, some/most API's will require you to explicitly specify the content type, before they return the "standard" HTTP response that your Javascript will read.
Resources:
https://web.archive.org/web/20210816145541/https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

Sending AJAX POST to PHP is not working?

I swear this was working properly earlier, but now it's not so I clearly messed something up.
I'm making a form where the inputted info gets AJAX posted to my PHP file, which just outputs the username and password. Right now I even hardcoded the data being sent to just a string and the php file just printing that for testing purposes. However, when I click submit, it doesn't go to my loginProcess.php page, but it just stays on the page and prints to the console "hello","success", and "test", which indicates it went through the full Process() function.
My url is correct and in the same directory as the index.html file. I've tried different things such as using $.post() or making the submit button a type="input". If you see the form line I commented out before the non-commented one, that's me trying to send the data directly without going through ajax and it works fine and outputs the loginProcess.php (however my project requires going through ajax). Anyone know what's going on?
Here's my html file:
<!DOCTYPE html>
<html>
<head>
<!-- <script src="frontEnd.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Login System</title>
</head>
<style>
</style>
<body>
<center>
<p><b>LOGIN SYSTEM</b></p>
<!-- <form id="login" action ="loginProcess.php" method="post"> -->
<form name = "loginform">
UCID:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br><br>
<button type="button" onclick = "Process()">Submit</button>
</form>
</center>
</body>
<script>
function Process() {
console.log("hello")
var ucid = document.loginform.username.value;
var pw = document.loginform.password.value;
$.ajax({
type:"POST",
url: "loginProcess.php",
data: "ajaxUCID=TESTUSERNAME",
success: function(){
console.log("success")
},
error: function(){
console.log("error")
}
});
// $.post("loginProcess.php",{ajaxUCID:"TESTUSERNAME"});
console.log("test")
}
</script>
Here's my loginProcess.php file:
<!DOCTYPE html>
<html>
<head><title>process</title></head>
<body>
<?php
$ucidPHP = $_POST["ajaxUCID"];
echo "Username is ".$ucidPHP;
// $pwPHP = $_POST["ajaxPW"];
// echo "Password is ".$pwPHP;
?>
</body>
</html>
Try this -
<script>
function Process() {
var ucid = document.loginform.username.value;
var pw = document.loginform.password.value;
$.ajax({
type:"POST",
url: "loginProcess.php",
data: {ajaxUCID:TESTUSERNAME},
success: function(){
console.log("success")
},
error: function(){
console.log("error")
}
});
}
</script>
Hope this will work for you.
When you click on your network tab of Google chrome or equivalent of the other browser and then send your Ajax request to observe your packet delivered what result do you have ?
If you have a packet with an error can you tell us witch one, and if you receive a good header (without errors) , check the information inside it to see if it throws correct informations, like the data form in your Ajax post.
After that if the information are correct and the data structure is correct, to test, I usually do the following code to test the entire post received :
if(isset($_POST)){
var_dump($_POST); // this will show all posts received
}
Let me know if it works for you ;)
I don't get your problem, the code is working with me and returning the result successfully.
I think you mean that why the returned results doesn't show on the same page of the form.
Here is the correct code and below it is the explanation
index.php
<!DOCTYPE html>
<html>
<head>
<!-- <script src="frontEnd.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Login System</title>
</head>
<style>
</style>
<body>
<center>
<p><b>LOGIN SYSTEM</b></p>
<!-- <form id="login" action ="loginProcess.php" method="post"> -->
<form name = "loginform">
UCID:<br>
<input type="text" name="username"><br>
Password:<br>
<input type="password" name="password"><br><br>
<button type="button" onclick = "Process()">Submit</button>
</form>
<div id="responseFromServer"></div>
</center>
</body>
<script>
function Process() {
console.log("hello")
var ucid = document.loginform.username.value;
var pw = document.loginform.password.value;
$.ajax({
type:"POST",
url: "loginProcess.php",
data: {"ajaxUCID":ucid},
success: function(response){
document.getElementById("responseFromServer").innerHTML = response;
console.log("success")
},
error: function(){
console.log("error")
}
});
// $.post("loginProcess.php",{ajaxUCID:"TESTUSERNAME"});
console.log("test")
}
</script>
the code you provided was actually working properly, its just you didn't pick the result to display it on your page.
that was done by adding a div where I will place the response.
<div id="responseFromServer"></div>
and in the success callback of the ajax call, I just catched the response sent back from the server and placed it right inside the div, like so:
document.getElementById("responseFromServer").innerHTML = response;
That should work
Update#1:
He wanted to redirect to the php page.
in plain English, you should use ajax requests when you want to work with the server, send requests or get results without reloading the page, you can read more here Getting Starting with AJAX
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.
so in your case that you want to redirect the user, you don't really want to use ajax in this case you can simply do that with plain html form tag.
a form tag can have multiple attributes, here we are concerned with 2 :
action
method
Here is how you can update the code to get to your results
first: the form part:
<form name = "loginform" method="POST" action="loginProcess.php">
UCID:<br>
<input type="text" name="ajaxUCID"><br>
Password:<br>
<input type="password" name="password"><br><br>
<button type="submit" >Submit</button>
</form>
I've added 2 attributes, which are:
method: I set it to POST, because this is the http request type which you accept on your server [your PHP file you used $_POST].
action: I set it to the relative path of the file which should recieve your request, in our case its "loginProcess.php"
Then I changed the name of the input where we enter the username or UCID to be the same as the one you are receiving in your PHP file.
in your php you were accepting a request parameter $_POST["ajaxUCID"] this means that you are accepting a POST request and you want a parameter called ajaxUCID , that must be the name of the input. this is why I did that <input type="text" name="ajaxUCID">
I have also stopped the onClick action on the button to prevent the ajax request, also I have changed its type to "submit" so that once its clicked, it will automatically submit the form for you.
I hope that helped now, if you need furthur help, leave a comment

Post Method to URL from a onclick function

I need help on something that sounds easy but is difficult for me.
So when someone clicks on this div:
<div onclick="<go to url sending data using the post method>">Click Me</div>
I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.
If you need to use div you can do it like this but I suggest that you use button or input of type submit.
<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>
Also you may use jQuery or some other JS library.
NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.
Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.
//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="someInput">
<div onclick="sendData()">Click Me</div>
<script>
function sendData(){
//get the input value
$someInput = $('#someInput').val();
$.ajax({
//the url to send the data to
url: "ajax/url.ajax.php",
//the data to send to
data: {someInput : $someInput},
//type. for eg: GET, POST
type: "POST",
//datatype expected to get in reply form server
dataType: "json",
//on success
success: function(data){
//do something after something is recieved from php
},
//on error
error: function(){
//bad request
}
});
}
</script>
You can use <form> to send data
<form action="yourpage.php" method="post">
//form contents
<input type="submit" value="Submit">
</form>
The action URL specifies the URL of the page to which your data has to be send.

Login to a site without redirect to that site using jQuery/ajax

I want to send a login form to a site without having the page redirect to that site but rather just display a blank page instead. I have been looking around and noticed jquery would help me with this but I haven't found a way to get it to work quite right so I was hoping for some advice. This is what I have right now.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="placeholderurl" method="post">
<input type="hidden" name="username" value = "placeholder"/>
<input type ="hidden" name="password" value = "placeholder"/>
<input type="submit"/>
</form>
<script>
$(document).ready(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
var formdata = $('#myForm').serialize();
$.ajax({
url: "placeholderurl",
type: "POST",
data: formdata,
cache: false,
success: function(data) {
alert("yeah");
//?code to display blank page after successful login??
},
error: function(){
alert("noo");
}
});
});
});
</script>
</head>
</html>
Currently, the code always goes into the "noo" error block. I'm not sure how to extract more information out of the error so I don't know exactly what is going wrong. Any advice/tips would be appreciated.
*Edit
The placeholderurl and placeholder are filled in with the correct information in my actual code. Also, the url I want to post to is not in the same domain as the function is being called from so ajax may not work for this(comment from Archer). Since this is the case, is there another way to get the desired behavior that I can try without using ajax. Thanks again.
I'd suggest watching your network traffic in something like Fiddler, Firebug, or Chrome's developer tools and see what the response is that is causing the error. I'm guessing your placeholderurl is on a different domain and your call is failing due to that.

Execute a python script on button click

I have an HTML page with one button, and I need to execute a python script when we click on the button and return to the same HTML page with the result.
So I need do some validation on return value and perform some action.
Here is my code:
HTML:
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue"></button>
JS:
function validate(){
if (returnvalue=="test") alert(test)
else alert ("unsuccessful")
}
What my python code is doing is some validation on the name entered in the text box and gives the return status.
But I need the result back on the same page, so I can do the form submission later with all the details. Any help will be appreciated
You can use Ajax, which is easier with jQuery
$.ajax({
url: "/path/to/your/script",
success: function(response) {
// here you do whatever you want with the response variable
}
});
and you should read the jQuery.ajax page since it has too many options.
Make a page(or a service) in python, which can accept post or get request and process the info and return back a response. It is better if the response is in json format. Then you can use this code to make a call on the button click.
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){
$.ajax({
type:'get',
url:<YOUR SERVERSIDE PAGE URL>,
cache:false,
data:<if any arguments>,
async:asynchronous,
dataType:json, //if you want json
success: function(data) {
<put your custom validation here using the response from data structure >
},
error: function(request, status, error) {
<put your custom code here to handle the call failure>
}
});
});
</script>
I hope this helps

Categories