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
Related
I have spent hours chasing this and hope someone has a simple answer. I am using fetch to execute a routine. The server does not seem to populate the post values. I simplified the code to try and isolate it. A simple html form makes js request which issues a fetch including post of username and pwd. The values get passed to the server but the target php page has the $_POST array empty. Code follows. Any ideas?
web page initiating the request
***
<html>
<head>
<script src="/js/2.js"></script>
</head>
<body>
<h1>Who are you?</h1>
<form action="" method=POST>
<label>User Name</label>
<input id=username type=text autocomplete='username' name=username>
<label>Password</label>
<input id=pwd type=password autocomplete='current-password' name=pwd>
<input type=submit value="log in" onclick="login();">
</form>
</body>
</html>***
javascript fetching the response from the php page
***
async function login(){
let content = "username=buddy&pwd=xxxxxxxxx";
let response = await fetch("http://example.com/lib/2.php",{method: "POST", body: content });
var text = await response.text();
if(text == 1){
window.open("http://example.com", "_self");
}else{
alert(text);
}
}***
**php page where post does not populate**
***
<?php
echo "user name is ".$_POST['username'];
?>***
UPDATE: It turns out there was nothing wrong with the code in the first place. The introduction of formdata working was a fluke. On further testing, it failed as well. In fact, execution of the code sometimes worked and sometimes did not. I traced the problem down to the user of session_start. I need to do more research on the use of session_start so I am not sure why it causes the problem but I suspect that the $_POST is being associated with the session id and some of the time the session ids match and the post is visible and in other cases the session ids are different and the post is missing.
I have PHP code which successfully gets the contents of a directory on my server.
I wish to then write this array to a specific div on my main html page (so that I can parse this later and use this information further)
Currently my PHP navigates me away from my current page to write this array which I want to prevent.
Furthermore I wish to do all of the PHP work on a button click, and return the values on the main html page after.
How can I do this???
My button on my html page is as follows:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
And my PHP code looks like this to carry out the work:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
}}
I have an array: "IfPresentArray" which I then wish to write to my main html page:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
Any help would be greatly appreciated as I am very new to PHP.
Thanks in advance
You need to use AJAX techniques to do this. Use a Javascript framework like jQuery to react to the button click, make a request to your PHP script, and then update the contents of the div.
See http://api.jquery.com/click/ for handling clicks, and http://api.jquery.com/jQuery.ajax/ for making the request.
Good luck!
You will need to use an ajax call. This allows your to click some div, send something to the server, receive a response and display an output in many different formats.
You can either reference the jQuery library in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
or just download it and save it whereever
Here is a basic ajax call:
<script>
$(document).ready(function(){
$('#someval').click(function(){
var content = $('#somecontenttoadd').val; //this could be many things... etc(.text, .html)
$.ajax({
type:'post',
url: 'PHP_Function.php',
data: 'action='+content,
success: function(resp){
$('#somediv').html(resp); //lets put the information into a div
//this could be anything response format like .val or .text instead of .html
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
HTML -- you can get rid of the tags and just use the id of the object.
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" id="someval"/>
As others said, AJAX is the solution, I will give you the code that works for me, so that you have an exact starting point.
As I understand you have a separate html page and a php file that includes your function.
In order to make this work you will have to implement a function with an AJAX call.
This should be placed in a javascript file and will be invoked after the form submit button is clicked on the html page.
The AJAX call will then invoke your php function, get the response data back from php.
The javascript function will update the html page in the end.
You will need three files:
main.html
script.js
function.php
Let me replace my original answer with a full example of the three files.
main.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="myForm" method="post" action="function.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</form>
<div class="modal-footer">
<button type="submit" form="myForm" class="btn btn-primary" id="SaveButton">Submit</button>
</div>
<div id="resultbox">
</div>
</div>
</body>
</html>
Here we included jQuery, our own javascript and bootstrap just to look better. the form action is our function.php, the form 'id' is used in our jQuery code. the "result box" box will display the response.
script.js
$(function(){
$("#myForm").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
//display data...
$("#resultbox").html(data.name).show;
}
});
return false;
});
});
this will override the default form submit behavior. I had a typo here in the original answer, I fixed it. url and data are taken from the html form, dataType is set to json, because we expect a json back.
function.php
<?php
echo json_encode(array('name' => $_POST['name']));
Our php code is just one line, we build an array and return it as json. You can then used in jQuery, just like any other json, as shown in the above code.
Recently I am confused about whether it's possible to send input/textarea data directly without being included in html <form>. I thought in web page, if we want to get information from user then send the text to authentication server, we must use <form> irrespective of in which way it's submitted.
But an anonymous reviewer of my paper claims that <html> can be bypassed by using an html5 tag "textarea" and JS AJAX post. While I did lots of experiments trying to implement his way but all failed.
I wonder if there is really some way to submit user info without using <form> tag?
Thank you
Thanks for everyone's reply.
Update: I followed "the_void"'s code and changed the url of AJAX to a ServerSocket (implemented by Java). The server was able to get the POST event, but it cannot read the "data" of AJAX. The following is the html code:
HTML
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
// information to be sent to the server
info = $('#foo').val();
$.ajax({
type: 'POST',
url: 'http://10.0.0.3:8888',
data: ({ foo: info }),
// crossDomain: true,
// dataType: 'json'
});
return false;
});
});
</script>
</head>
<body>
<label>Text</label>
<textarea id="foo"></textarea>
<button id="submit">Submit via Ajax</button>
</body>
</html>
It seems that the socket server cannot read from AJAX (but it can read from < form > + < action >). Is there any way to fix the reading issue?
Thank you
Ajax (Asynchronous Javascript & XML) is a way to send data from client to the server asynchronously. For that you'd have to write code for sending the data in the client-side using Javascript/HTML and also to process the received data using server-side languages (eg PHP) on the server-side.
And, yes you don't need a <form> tag to do so.
Check out this example.
HTML:
<label>Text</label>
<textarea id="foo"></textarea>
<button id="submit">Submit via Ajax</button>
Javascript:
$('#submit').click(function(e) {
e.preventDefault();
// information to be sent to the server
var info = $('#foo').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {foo: info}
});
});
Server-side Handler (PHP): server.php
<?php
// information received from the client
$recievedInfo = $_POST['foo'];
// do something with this information
See this for your reference http://api.jquery.com/jquery.ajax/
Perhaps your reviewer was referring to the HTML5 textarea attribute "form". It allows a textarea to be part of a specified form without being inside the form element.
http://www.w3schools.com/tags/att_textarea_form.asp
But generally speaking, as long as you can identify an element, say a textarea, you can access the text inside it and send it to the server without submitting any forms using ajax.
From Sable's comment:
http://api.jquery.com/jquery.post
OR
http://api.jquery.com/jquery.ajax/
Yes, you can submit data to a server without putting it into a form. Form's provide a simpler mechanism for sending larger amounts of data to a server without the developer having to tell the browser how to encode the form.
EG:
HTML
JS
var text = $("input[type='text']").val();
$.post("/my/server/url", { userInput : text }, function(data){ /* Success! */});
This would technically post the data to the server without a form.
I have a HTML form in a Mason component(A.m) that uses the post method to call another Mason component(B.m). I want this Mason component(B.m) to return a value to the HTML form in the Mason component(A.m). Then I want to pass this returned value to a Javascript function.
How can I do this? I'm new to web development.
You need to make an AJAX request. Although not strictly necessary, I would suggest you to use jQuery, it will make things a lot easier. Please also have a look at this question: jQuery AJAX submit form
Here's a little example in Mason, it's very simplified of course, you should add some error checking and some escaping also, but I think it could be a good start. Your A.mc component could look like this:
<html>
<head>
<title>This is A</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#myform").submit(function() { // intercepts the submit event
$.ajax({ // make an AJAX request
type: "POST",
url: "B", // it's the URL of your component B
data: $("#myform").serialize(), // serializes the form's elements
success: function(data)
{
// show the data you got from B in result div
$("#result").html(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form
});
});
</script>
</head>
<body>
<form id="myform">
<input type="text" name="mytext" />
<input type="submit" />
</form>
<div id="result"></div>
</body>
</html>
it's just an HTML page that loads jQuery library and that contains your form, and that contains some code to instruct the form to make an AJAX request to B component when the user clicks the Submit button and then to show the contents returned by B component in your result div.
And this could be your B.mc component:
<%class>
has 'mytext';
</%class>
I got this text <strong><% $.mytext %></strong> from your form,
and its length is <strong><% length($.mytext) %></strong>.
Result will be like this:
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.