Sending values to the action script continuously. How to do that? - javascript

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>

Related

submitting form to PHP page without reloading using the submit button

Hello friends please am new to jquery and javascript so i copied the code I want to send form to a php page without reloading the page, this code works but i want to click the submit button to send the form and not the enter key:
<input type="text" id="name" name="name" /><br><br>
<input type="text" id="job" name="job" /><br><br>
<input type="submit" id="submit" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "fell.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
}
});
};
});
});
</script>
To make the click of the submit button work you should wrap your code in a form element then change your JS code to hook to the submit event of that form. Note that will also give you the 'submit on enter keypress' action by default, so your current keypress handler can be removed. Try this:
<form id="my-form">
<input type="text" id="name" name="name" /><br><br>
<input type="text" id="job" name="job" /><br><br>
<input type="submit" id="submit" />
</form>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#my-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "fell.php",
data: $(this).serialize(),
success: function(status) {
console.log('AJAX call successful');
console.log(status);
}
});
});
});
</script>
You are not name the submit button. Try to give name to submit button and try below:-
<form id="myFrom" onsubmit="submitForm();">
<input type="text" id="name" name="name" /><br><br>
<input type="text" id="job" name="job" /><br><br>
<input type="submit" id="submit" name="submit" />
</form>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
});
function submitForm(){
$.ajax({
method: "POST",
url: "fell.php",
data: $("#myFrom").serialize(),
success: function(status) {
alert("successfull");
}
});
return false;
}
</script>

Ajax not working on PHP page

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

Inserting Data into MySQL without calling PHP file inside HTML

I have a form:
<form method="post" action="insert.php">
<input type="text" name="firstname" placeholder="Vorname" required>
<br>
<input type="text" name="lastname" placeholder="Nachname" required>
<br>
<input type="text" name="nickname" placeholder="Spitzname" required>
<br>
<input type="email" name="email" placeholder="Email" required>
<br>
<input type="submit" value="Speichern">
</form>
As you can see my action is action="insert.php" so that calls my insert.php. A new url is created and it is opened in the browser.
But what if i dont want that? I want to stay on the same site where the form is and i would prefer not to call any php directly. i would prefer to call a javascript function. For example, my select i do with ajax:
function getData() {
$.ajax({
url: "queries.php",
data: {action: "retrieve_data"},
dataType: "json",
type: "post",
success: function(output) {
// do stuff
}
});
}
Can i also do something like that with the insert?
<html>
<body>
<form method="post" action="insert.php" id="insertForm">
<input type="text" name="firstname" placeholder="Vorname" required>
<br>
<input type="text" name="lastname" placeholder="Nachname" required>
<br>
<input type="text" name="nickname" placeholder="Spitzname" required>
<br>
<input type="email" name="email" placeholder="Email" required>
<br>
<input type="button" id="insertData" value="Speichern">
</form>
<script type="text/javascript" src="lib/js/jquery-2-1-3.min.js"></script>
<script type="text/javascript">
$(function () {
$('#insertData').click({ inputs:$('#insertForm :input') }, getData);
});
function getData(o) {
var values = {};
o.data.inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajax({
url: "queries.php",
data: {action: "retrieve_data", firstname: values['firstname'], lastname: values['lastname'], nickname: values['nickname'], email: values['email']},
dataType: "json",
type: "post",
success: function(output) {
// do stuff
}
});
}
</script>
</body>
</html>
Here you go, you can always edit is as you want, or what values are optional and such.
Remember i've used a type="button" so the page doesn't reload, so the action could just stay empty.
Since you seem to be using jQuery, this is easy; as explained in the documentation. If you give your form id=insertForm this should work:
$("#insertForm").submit(function(e){
$.ajax({
url: "/insert.php",
type: "post",
data: $(this).serialize();
});
e.preventDefault();
});

run php script with ajax shows no result

I'm trying to run a php script using ajax after a form submission.
this is the form
<form id="form" class="form">
<input id="email" type="email" required name="email" placeholder="Email" onchange="myUpdateFunction()" value="">
<textarea id="message" type="text" value="" name="message" onchange="myUpdateFunction()" required placeholder="Comments" style="border:none;border-bottom:1px solid #424242; width:530px;"></textarea>
<input id="submit" type="submit" class="submit" name="send_request" value="Submit" >
</form>
this is my script
$('.submit').on('click', function() {
$.ajax({
url: "send.php",
method:'post',
data: {'email': $('#email').val(), 'message': $('#message').val()}
}).done(function() {
alert('Message Sent.');
});
});
and this is my send.php file
<?php
if(isset($_POST['send_request'])){
//send email
}
?>
but it doens't work, the page is reloaded, the email is not sent and no "alert message" is displayed
there is no problem in php because if I delete the javascript and I add action="send.php" method="POST" as attributes in the form it works, so I think that the problem is the javascript
http://jsfiddle.net/o5xvpkmv/2/
You shouldn't use the onchange or the click event for this kind of stuff, but the submit event (preventing the default behaviour of submit button).
<form id="form" class="form">
<input id="email" type="email" name="email" placeholder="Email" required>
<textarea id="message" type="text" value="" name="message" placeholder="Comments" required></textarea>
<input id="submit" type="submit" class="submit" name="send_request" value="Submit">
</form>
$("#form").on('submit', function(e) {
e.preventDefault();
$.ajax({
url: "send.php",
method:'post',
data: $( this ).serialize()
}).done(function() {
alert('Message Sent.');
});
});
or (both ways are good)
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
url: "send.php",
method: 'post',
data: $(this).serialize()
}).done(function () {
alert('Message Sent.');
});
return false;
});
});
Also, about the backend, you should make this kind of check:
if (
isset($_POST["email"]) &&
!empty($_POST["email"]) &&
isset($_POST["message"]) &&
!empty($_POST["message"])) {
//send email
}

Can't submit my form twice with ajax

Hey everyone, I have some problems with a (I think simple) form submitting with ajax.
The first time the user submit the form, everything goes OK: The content of the div changes and the php is processed. But if there is no match in my DB it will return "f" and the javascript will write back an unusable form that can't be re-submitted with ajax.
The HTML:
<div class="maincontainer" id="login">
<form id="loginform" onsubmit="void login();return false;">
<input name="username" type="text" class="textboxinput" id="username" autocomplete="off" />
<input name="password" type="password" class="textboxinput" id="password" autocomplete="off" />
<input type="submit" name="button" class="button" id="button" value="Login" />
</form>
</div>
The Javascript:
function login(){
//Change the box content to "Logging in"
$("#login").html("<p style='line-height:170px;text-align:center;width:100%;margin:0px;padding:0px;'>Logging in</p>");
//Get the values of the username and password field
var username = $('#username').val();
var password = $('#password').val();
//Make the ajax request
$.ajax({
datatype: "text",
type: "POST",
url: "process.php",
data: "username=" + username + "&password=" + password,
success: function (m) {
//If there's no match, rewrite the form in the div
if ( m == "f"){
content= " <form id='loginform' onsubmit='void login();return false;'><input name='username' type='text' class='textboxinput' id='username' autocomplete='off' /><input name='password' type='password' class='textboxinput' id='password' autocomplete='off' /><input type='submit' name='button' class='button' id='button' value='Login' /> <p style='font-size:small;'>Login failed, please try again</p></form>";
$("#login").html(content);
}
}
});
};
EDIT
I didn't find the problem but I did find a solution which is not to erase my form, only hide it
HTML:
<div class="maincontainer" id="login">
<div id="errorbox"></div>
<form id="loginform" onsubmit="return login();">
<input name="username" type="text" class="textboxinput username" id="username" value="username" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value='username'" autocomplete="off" />
<input name="password" type="password" class="textboxinput password" id="password" value="password" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value='password'" autocomplete="off" />
<input type="submit" name="button" class="button" id="button" value="Login" />
<div id="errorshow">RegisterForgot your login infos?</div>
</form>
</div>
Javascript:
function login(){
var username = $('#username').val();
var password = $('#password').val();
//Do security checks here
$("#loginform").hide();
$("#errorbox").html("<p class='logloading'>Logging in</p>");
$.ajax({
datatype: "text",
type: "POST",
url: "login.php",
data: "username=" + username + "&password=" + password + "&method=js",
success: function (m) {
if ( m == "f"){
$("#errorbox").html("");
$('#username').val("");
$('#password').val("");
$("#loginform").show();
$("#errorshow").html("<p class='errormsg'>Wrong username/password combination</p>");
$("#username").focus();
}
else{
window.location = m;
}
}
});
return false;
};
Oh, and I should thank everybody that commented here (and posted) every info helped me a bit.
Just a fix, not an explicit answer to your original question.
I'd use
data: $('#form_id').serialize()
instead of manually doing all of this:
data: "username=" + username + "&password=" + password,
What happens when the user submits a space? Your query breaks.
Just make sure the username box has a name of username and the password box follows the same pattern.
EDIT
This code is a bit odd:
onsubmit='void login();return false;'
Instead of manually inputting this, try this code (just delete that part and insert this):
$('#loginform').live('submit', function(e) {
login();
e.preventDefault()
});
I think I ran into this problem a while back as well.
A plausible workaround would be to put the login function on the onclick of the submit button instead (and have that return false as well)

Categories

Resources