I have a python script file that returns a json
{"message": "Login or password is empty", "success": 0}
I want to go to this url in html and dislpay "Login or password is empty" and also save the success int to be used later for pass fail verification.
I have no idea how to get the json parsed so that I can use it in html.
This is my html
<h2> Login</h2>
<form action="http://test.com/cgi-bin/login.py" method="POST" target="hiddenFrame2">
Username:<br>
<input type="text" name="username">
<br>
Password:<br>
<input type="password" name="password">
<br>
<br>
<input type="submit" value="Submit">
<br>
<iframe src="about:blank" frameborder="0" width="100" height="50" scrolling="no" name="hiddenFrame2" class="hide"></iframe>
<br>
<br>
</form>
Suppose you have form like this,
<h2> Login</h2>
<form action="http://test.com/cgi-bin/login.py" method="POST" target="hiddenFrame2" id="myform">
Username:<br>
<input type="text" name="username">
<br>
Password:<br>
<input type="password" name="password">
<br>
<br>
<input type="submit" value="Submit">
<br>
<iframe src="about:blank" frameborder="0" width="100" height="50" scrolling="no" name="hiddenFrame2" class="hide"></iframe>
<br>
<br>
</form>
<span id="log"></span>
You can submit your form like this using ajax,
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="application/javascript">
$(document).ready(function(){
$("#myform").submit(function(){
var formvars = $("#myform").serialize();
var url = "http://test.com/cgi-bin/login.py";
$.ajax({
url: url,
dataType: 'text',
data : formvars,
type:"POST",
success: function(data){
alert( data );
var json = eval(data);
var success = json.success;
var message = json.message;
if(success =="1")
$("#log").text(message); // Success
else
$("#log").text(message); // Failed
},
error: function(data){
alert('error; '+ data);
}
});
return false;
});
});
</script>
Related
I created a contact form for a Wordpress theme (custom) using jQuery/Ajax. When I tested the wp_send_json_sucess with "it works" it returned as suspected. However, when I added $formdata and the name of a field on the form the from returned undefined in the JS alert box. I'm pretty sure I've typed it correctly, as I was following this tutorial: https://www.youtube.com/watch?v=LYvx_L9ESn0. But I cannot seem to get it to work.
Code for functions.php here
add_action('wp_ajax_contact', 'contact_form');
add_action('wp_ajax_nopriv_contact', 'contact_form');
function contact_form()
{
$formdata = [];
wp_parse_str( $_POST['contact'], $formdata );
wp_send_json_success( $formdata ['myName'] );
}
Form Code Here :
<form id="contact">
Name: <input type="text" name="myName" class="contactform
fields" placeholder="name"required><br><br>
Email: <input type="text" name="myEmail" class="contactform
fields" placeholder="you#youremail.com" required><br><br>
<p>What is your inquiry regarding?</p><be>
<input type="radio" name="reason" value="general">
<label for="news">General Inquiry</label><be>
<input type="radio" name="reason" value="course">
<label for="news">Courses</label><br>
<p class="contact_txt">Your Message:</p>
<textarea name="msg" rows="5" cols="700" placeholder="begin
typing message here..." required>
</textarea>
<p class="contact_txt">Would you like to subscribe to our
newsletter?</p>
<br>
<input type="checkbox" name="news" value="Subscribe">
<label for="news">Yes, I would like to subscribe</label>
<br>
<input class="btns" name="btn-send" id="mySubmit" type="submit" value="submit">
<input class="btns" name="btn-reset" id="myReset" type="reset" value="reset">
</form>
Script Here :
<script>
jQuery('#contact').submit( function(event){
event.preventDefault();
var endpoint = '<?php echo admin_url('admin-ajax.php' ); ?>';
var form = jQuery('#contact').serialize();
var formdata = new FormData;
formdata.append('action', 'contact');
formdata.append('contact', 'form');
jQuery.ajax(endpoint, {
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function(res){
alert(res.data);
},
error:function(err){
}
})
})
</script>
I have a textarea input on my page that I want to post to the server using AJAX. The AJAX call is good, however, it will not see the value that's inside the textarea.
My HTML:
<div class="promptBody">
<div id="promptText" onclick="replaceWithInput(this)">
<p class="promptBody"><div id="prompty">{{prompt.prompt|linebreaks}}</div></p>
</div>
<form id="promptUpdateForm">
<div id="promptInput">
<p><textarea class="input" cols="40" id="id_prompt" name="prompt" placeholder="Prompt" rows="10"></textarea></p>
<p><input class="submit" type="submit" name="submit" id="submit" value="Edit Prompt" /></p>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('submit', '#promptUpdateForm', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/apps/litprompt/a/{{prompt.id}}/update/',
data: {
'prompt': $('#id_prompt').val(),
csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val(),
},
success: function(json) {
$('#promptText').html(json.prompt_data);
var promptText = document.getElementById('promptText');
var promptInput = document.getElementById('promptInput');
promptText.style.display = 'block';
promptInput.style.display = 'none';
}
});
});
});
</script>
If I change my ajax code in data to 'prompt': 'blah', it works just fine. But every time I post with 'prompt': $('#id_prompt').val(), it is a null value.
The textarea HTML element is not self-closing. It has to be closed by </textarea>.
See as follows:
<div class="promptBody">
<div id="promptText" onclick="replaceWithInput(this)">
<p class="promptBody"><div id="prompty">{{prompt.prompt|linebreaks}}</div></p>
</div>
<form id="promptUpdateForm">
<div id="promptInput">
<p><textarea class="input" cols="40" id="id_prompt" name="prompt" placeholder="Prompt" rows="10"></textarea></p>
<p><input class="submit" type="submit" name="submit" id="submit" value="Edit Prompt" /></p>
</div>
</form>
</div>
I am trying to understand the basics of using AJAX in conjunction with PHP in order to use php pages to provide functions, but not change my 'view' on my MVC design.
So I created this basic login page...
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$(#"login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
};
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
</form>
<div id="message"></div>
<div>
</body>
</html>
And this was my php page to "handle" to login...
<?php
$is_ajax = $_REQUEST['is_ajax'];
if(isset($is_ajax) && $is_ajax)
{
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username == 'demo' && $password == 'demo')
{
echo 'success';
}
}
?>
The problem I am having is that whenever I submit my login, I am redirected to "/loginForm.php" instead of staying on my current page and having the message change underneath the login form.
I tried using Firebug to help me track down what I suspected to be a javascript error, but to no avail.
Any idea on why I am being redirected or why the form is not submitting via Ajax?
One more mistake here
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
}); <--- You Missed ")" here
}
a small mistake
$(#"login").click(function() {
This should be
$("#login").click(function() {
^ // # inside quotes.
Besides the typo and Rocky's good catch on the }); <--- You Missed ")" here
Both your username and password fields are the same.
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
and
<label for="password"> Password: </label>
<input type="text" id="username" name="username" />
the 2nd one should read as
<input type="text" id="password" name="password" />
In using everyone's answer, you will have yourself a working script.
Remember to hash your password once you go LIVE.
Edit sidenote: I've made a note below about using a button, rather than an input.
Here's a rewrite, just in case. However that input needs to be a <button>.
<!DOCTYPE html>
<head>
<title>learning Php</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function() {
var action = $("#form1").attr("action");
var form_data = {
username: $("#username").val(),
password: $("#password").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
{
$("#form1").slideUp('slow', function() {
$("#message").html('<p class="success">You have logged in.</p>');
});
}
else
$("#message").html('<p class="error">Incorrect password or username.</p>');
}
});
return false;
});
});
</script>
</head>
<body>
<div>
<form name="form1" id="form1" method="post" action="loginForm.php">
<p>
<label for="username"> Username: </label>
<input type="text" id="username" name="username" />
</p>
<p>
<label for="password"> Password: </label>
<input type="text" id="password" name="password" />
<!--
Your original input
<input type="text" id="username" name="username" />
-->
</p>
<button type="submit" id="login" name="login" />LOGIN</button>
<!--
Your original submit input. Don't use it
<p>
<input type="submit" id="login" name="login" value="login" />
</p>
-->
</form>
<div id="message"></div>
</div>
</body>
</html>
Your last div just before </body> was unclosed </div>, I've changed that above.
Additional edit from comments.
It seems that there was probably a space inserted somewhere and the use of trim() was the final nail to the solution.
response.trim();
A special thanks goes out to Jay Blanchard to have given us a helping hand in all this, cheers Sam!
References (TRIM):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
http://php.net/manual/en/function.trim.php
I want to repeatedly send values of username and password to the php script. How do I do this ? Like to send the values to the action script, we use submit button but how can I send the values automatically to the script and that too continuously ?
<form method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
Using the jQuery form plugin you can do the following:
setInterval(function() {
$('form').ajaxSubmit();
}, 1000);
Another solution is to target the form to an iframe so if you submit the form, it doesn't reload the page:
HTML:
<form id="myform" method="post" action="processor.php" target="frm">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<iframe name="frm" id="frm"></iframe>
JS:
var form = document.getElementById('myform');
setInterval(function() {
form.submit();
}, 1000);
try something like this
JAVASCRIPT
<script language=javascript>
var int=self.setInterval(function(){send_data()},1000);
function send_data()
{
document.getElementById('my_form').submit()
}
</script>
HTML
<form method="post" id="my_form" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
</form>
<form id="myform" method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<script type="text/javascript">
var count=100,i=0;
for(i=0;i<count;i++) {
document.getElementById('myform').submit();
}
</script>
This will submit the form 100 times
Use Ajax, it's really easy with jQuery. To send the form data to the processor.php script:
var sendForm = function () {
$.ajax({
type: 'post',
url: 'processor.php',
dataType: 'JSON',
data: {
username: $('#username').val(),
password: $('#password').val()
},
success: function (data) {
// do something with the answer from server?
},
error: function (data) {
// handle error
}
});
}
So, sendForm is a function that sends the form data to the server. Now, wee need to set a timer that will invoke it repeatedly:
window.setInterval(sendForm, 1000); // sends form data every 1000 ms
You may you $.post or $.get or $.ajax request repeatedly to send continuous request.
$(document).ready(function(){
setInterval(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
//your code what you want to do of response
alert(response);
});
}, 1000);
});
and html code is like following
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>
This is a full HTML file doing what you want, read the comments.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post" action="processor.php">
<input type="username" id="username" value="suhail" />
<input type="password" id="password" value="secret_code" />
<input type="submit" />
</form>
<script>
function send_request(username, password) {
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
// You can check if the login is success/fail here
console.log(response);
// Send the request again, this will create an infinity loop
send_request(username, password);
});
}
// Start sending request
send_request($('#username').val(), $('#password').val());
</script>
Try this,
JS:
$(document).ready(function(){
var int=self.setInterval(function(){statuscheck()},1000);
function statuscheck()
{
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type:"post",
url:"processor.php",
dataType: "html",
cache:false,
data:"&username="+username+"&password="+password,
success:function(response){
alert(response);
}
});
}
});
HTML:
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>
I have two forms with id formA and comments and I want to submit them via AJAX. But the if and else here doesn't check the form. I always get alert hello3.
JS:
function submitformbyajax() {
var currentForm = $(this);
if (currentForm.attr("id") == 'formA') {
$.ajax({
type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function() {
$("#refresh").load("commentform.php #refresh");
}
});
} else if (currentForm.attr("id") == 'comments') {}
alert("hello3");
return false;
}
the function is called by
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
here is the full demo page ....
<?php
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script>
function submitformbyajax (){
var currentForm = $(this);
if (currentForm.attr("id") == 'formA' ) {
$.ajax({type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function(){
$("#refresh").load("commentform.php #refresh");
alert ("hello1");
}
} );
}
else if (currentForm.attr("id") == 'comments') {
alert("hello2");
}
alert ("hello3");
return false;
}
</script>
<title>
comment forms..
</title>
</head>
<body>
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
<div id="refresh">
<?php
include_once('databaseconnection.php');
$selectdata=mysql_query("select * from `fetwork_view` ");
while($selectedinarray=mysql_fetch_array($selectdata)){ ?>
<table>
<tr>
<td>
<?=$selectedinarray['view']?>
</td>
</tr>
<tr>
<td>
<form name="comment" id="comments" action="" method="">
<textarea name="comment" id="commentform" style="width:70%; height:25px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</td>
</tr>
</table>
<?php } ?>
</div>
</body>
</html>
Your alert(...) statement is executed regardless of condition tested by if. It is executed right after that if.
Note that ajax will not redirect the "flow" of the code. Browser will just "launch" the AJAX request and continue. Then, after a response from server is received - AJAX callback function will be executed.
Update:
To "pass" your form to submitformbyajax function add this as an argument:
<form name="formA" id="formA" onsubmit="submitformbyajax(this);">
JS:
function submitformbyajax(your_form) {
var currentForm = $(your_form);
I think you should use
$("form#formA").submit(function(){
alert(1);
});