Not getting any response with ajax - php

I made a simple script to insert data to database using ajax and jquery . It seems that I am not receiving back any response , and I don't think I am doing something wrong . So , can anybody take a look and help me ?
process.php
<?php
$id = $_POST['id'];
$user= $_POST['username'];
$password = $_POST['password'];
$con = mysqli_connect('localhost','root','','car_rental');
$query = 'insert into car_admin (admin_id,admin_username,admin_password) values(?,?,?)';
$query = $con->prepare($query);
$query-> bind_param('iss',$id,$user,$password);
if($query->execute()) { echo "done";}
else { echo "failed"; }
$query->close();
$con->close();
?>
register.php
<script src="jquery-1.12.4.js"></script>
<script src="script.js"></script>
<form id="register" method="POST" >
<fieldset>
<legend>
Register
</legend>
ID: <input id="id" type="text" name="id" value="" />
Username : <input id="username" type="text" name="username" value="" />
Passsword : <input id="password" type="password" name="password" value="" />
<input id="submit" type="submit" name="submit" value="Register" />
</fieldset>
</form>
<div id="result"></div>
jquery
$(document).ready( function() {
$('#submit').click(function() {
var id = $('#id').val();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type:'post',
url:'process.php',
data:'id='+id+'username='+username+'password='+password,
success:function(data){
$('#result').html(data);
}
});
});

Prevent the form from submitting via the browser
You need to change your code to include the correct formatting
data:'id='+id+'&username='+username+'&password='+password,
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<form id="register" >
<fieldset>
<legend>
Register
</legend>
ID: <input id="id" type="text" name="id" value="" />
Username : <input id="username" type="text" name="username" value="" />
Passsword : <input id="password" type="password" name="password" value="" />
<button id="submit" name="submit" />Register</button>
</fieldset>
</form>
<div id="result"></div>
<script>
$(document).ready( function() {
$('#submit').click(function(e) {
e.preventDefault(); // Prevent the form from submitting via the browser
var id = $('#id').val();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type:'post',
url:'login.php',
data:'id='+id+'&username='+username+'&password='+password,
success:function(data){
$('#result').html(data);
}
});
});
});
</script>

The reason your ajax is failing is because you are not posting the parameters correctly. If ID is 1, username is "Username", and password is "password", the following code will return the value shown.
'id='+id+'username='+username+'password='+password,
id=1username=Usernamepassword=Password
You need to change your code to include the correct formatting, as per below.
'id='+id+'&username='+username+'&password='+password,
Then your Ajax request should work. I can see no problems with your PHP. I would also suggest doing an encodeURIComponent as if your strings contain any URI characters, it will cause further problems. Take a look at this tutorial as it is an excellent example of making an Ajax request.

Related

Load php form on submit

I have an admin panel where I have an option to add a user into database. I made a script so when you click the Add User link it will load the form where you can introduce the user infos. The thing is, I want to load in the same page the code that is run when the form is submited.
Here's the js function that loads the file:
$( ".add" ).on( "click", function() {
$(".add-user-content").load("add-user-form.php")
});
and here's the php form
<form id="formID" action="add-user-form.php" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
}
?>
Maybe I was not that clear, I want this code
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
to be outputted in the same page where I loaded the form because right now it takes me to the add-user-form.php when I click the submit button.
Thanks for your help!
if you do this the code will be redirected on post to your page:
<form name="formID" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
you should add a validation so it doest show the form if you receive $_POST['add-user']
You have to submit your for via ajax.
Alternatively you don't need to load form html, just hide the form and on add user button click show the form.
Check this code. Hope that helps you :-
// Add User Button
<div class="color-quantity not-selected-inputs">
<button class="add_user">Add User</button>
</div>
// Append form here
<div class="add_user_form"></div>
// for posting response here
<div class="result"></div>
Script for processing form and appending user form
<script>
$(function(){
$( ".add_user" ).on( "click", function() {
$(".add_user_form").load("form.php")
});
$(document).on("submit","#formID", function(ev){
var data = $(this).serialize();
console.log(data);
$.post('handler.php',data,function(resposne){
$('.result').html(resposne);
});
ev.preventDefault();
});
});
</script>
form.php
<form id="formID" action="" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
handler.php
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
die;
}
?>
What you are looking for is to submit the form using AJAX rather than HTML.
Using the answer Submit a form using jQuery by tvanfosson
I would replace your
<input type="submit" name="add-user" value="Add User">
with
<button id="add-user-submit">Add User</button>
and then register an onClick-handler with
$( "#add-user-submit" ).on( "click", function() {
$.ajax({
url: 'add-user-form.php',
type: 'post',
data: $('form#formID').serialize(),
success: function(data) {
$(".add-user-content").append(data);
}
});
});
to add the actual submit functionality.

I'm trying to send username and password to a php file using AJAX with post method. How to retrieve fields

How to access these variables ?
I'm trying to retrieve username and password in php files, But, it says Undefined index username if I use $_POST['Username'}
<script>
var a = new XMLHttpRequest();
a.onreadystatechange = function(){
if (a.readyState==4 && a.status==200) {
ajaxFinished = true;
alert(a.responseText);
}
else {
}
}
a.open("post","php/psswd.php",true);
a.send('"Username="+document.getElementByNames("Username")+"&Password="+getElementByNames("Password")'); // posting username and password
</script>
How to retrieve these fields in php file ?
I found out the answer myself, the problem was that,
a.setRequestHeader("Content-type","application/x-www-form-urlencoded");
needs to be added. And document.getElementsByName('xyz') returns nodeList, but not perticular node, We need to traverse that nodeList.
instead of using the XMLHttpRequest method, take a look at this:
<script type="text/javascript">
$('#loginForm').submit(function(e) {
var username = $("#login-username").val(); //id of the form text input
password = $("#login-password").val(); //id of the form text input
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: { form: 'login', username: '' + username + '', password: '' + password + ''}
}).success(function( msg ) {
//msg is the text returned from the PHP function that will validate the login
$('.login_success_text').html(msg);
});
});
</script>
<body>
<form role="form" name="loginForm" id="loginForm" method="POST">
<label>Username</label>
<input id="login-username" class="form-control text placeholder" placeholder="Username" name="username" type="text">
<label>Password</label>
<input id="login-password" class="form-control password placeholder" placeholder="Password" name="password" autocomplete="off" type="password">
<input type="submit" value="Login" />
<div class="login_success">
<span class="login_success_text"></span>
</div>
</body>
The syntax is getElementsByName and not the way you presently have getElementByNames
The word Elements is pluralized, not Names.
<script>
var a = new XMLHttpRequest();
a.onreadystatechange = function(){
if (a.readyState==4 && a.status==200)
{
ajaxFinished = true;
alert(a.responseText);
}
else
{
}
}
a.open("post","php/psswd.php",true);
a.send('"Username="+document.getElementsByName("Username")+"&Password="+getElementsByName("Password")'); // posting username and password
</script>
For more information on this, visit:
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName
Edit
The following works using jQuery and tested with FF 28.0 and IE 7.
Sidenote: You may want to change this window.location = "success.php"
<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function chk_ajax_login_with_php(){
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
var params = "username="+username+"&password="+password;
var url = "php/psswd.php";
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("status").innerHTML= 'checking...' ;
},
complete: function() {
},
success: function(html) {
document.getElementById("status").innerHTML= html;
if(html=="success"){
window.location = "success.php"
}
}
});
}
</script>
</head>
<body>
<div id='logindiv'>
<label>Username:</label>
<input name="username" id="username" type="text">
<label>Password:</label>
<input name="password" id="password" type="password">
<input value="Submit" name="submit" class="submit" type="submit" onclick='chk_ajax_login_with_php();'>
<div id='status'></div>
</div>

POST a form to colourbox iframe and open th result in iframe itself

I have a form
<form method="POST" action="qwerty.php" />
<input type="text" name="merchant" />
<input type="text" name="password" />
<input type="submit" value="go" />
</form>
What I am trying to do is post this values into this php and get the result or reponse open up in the modal window it self.Is this possible? Any help?
EDIT :
Using Ajax and jquery this can be achieved like:
var merchant = $('form input:nth-child(1)').val();
var password= $('form input:nth-child(2)').val();
$('form input[type="submit"]').click(function() {
$.post( "qwerty.php", { merchant: merchant, password: password }, function(data) {
// #extraDiv is a div with display:none that will serve as a wrapper for the data
$('#extraDiv').html(data).colorbox();
});
});
Then in qwerty.php pick up the values u sent:
$merchant = $_POST['merchant'];
$password= $_POST['password'];
I am not so familiar with colorbox, but the above might work.

An AJAX method I am trying to use is disabling another jQuery method

This chunk of AJAX
$('input#adminLogin').on('submit', function() {
var username = $('#username').val();
var password = $('#password').val();
if (username == '' || password == '')
$('#errForm').fadeIn(200).text('You must enter a username and password');
else {
$.ajax ({
type: 'post',
url: '/classes/login/Authenticator.php',
data: $('#login_form').serialize(),
cache: false,
success: function(data) {
if(data == 'You entered an invalid username or password');
$('.actionDiv').fadeIn(200).html(data);
else
$('.fade_bg').fadeOut(200);
}
});
}
});
Is making this jQuery
$('a#aLogin').on('click', function (e) {
e.preventDefault();
$('.fade_bg').fadeIn(200);
$('a#aLogin').hide();
});
not work, whether or not I have e.preventDefault() in the AJAX method. How come?
HTML
<div class="fade_bg">
<div class="actionDiv">
<span id="errForm"></span>
<form id="login_form" action="./classes/login/Authenticator.php" method="post">
<p>username: <input type="text" name="username" id="username" /></p>
<p>password: <input type="password" name="password" id="password" /></p>
<p><input type="submit" name="adminLogin" value="Log in" id="adminLogin" /></p>
</form>
<p><a id="cancelLogin" href="">Cancel</a></p>
</div>
<div id="topRight">
<a id="aLogin" href="">Admin login</a>
<form id="exit" action="./classes/login/ExitDoor.php" method="post">
<p>
<?php
if ($_SESSION['logged-in'] == 1)
print '<span id="greeting">Welcome, ' . $_SESSION['firstName'] . ' | </span>';
?>
<input id="aLogout" type="submit" name="adminLogout" value="Log out" />
</p>
</form>
</div>
You have a syntax error in your first snippet. That's why the second one isn't executed anymore.
Remove the semicolon at the end of this line
if(data == 'You entered an invalid username or password'); <--
All major browser have built-in developer tools. You can find such errors very quick by having a look at the developer console.
In your example chromes console would show you this - http://i43.tinypic.com/xqg48.jpg

submitting two forms via javascript without click

i am using the following code to auto-submit a form
<script type="text/javascript">
$(function () {
$('#submit').click();
});
</script>
<div style="display:none">
<form method="post" action="http://mydomain/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form>
</div>
i want to submit the same data to two urls ...
http://mydomain/texting/register.php?list_id=15
http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>
how can edit my code to submit same form data automatically?
i tried this code
<script type="text/javascript">
function submitTwice(f){
f.action = 'http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>';
f.target='ifr1';
f.submit();
f.action = 'http://mydomain.com/texting/register.php?list_id=15';
f.target='ifr2';
f.submit();
}
</script>
*/
<script type="text/javascript">
$(function () {
$('submitTwice(f)').click();
});
</script>
<div style="display:none">
<iframe name="ifr1" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=<?php echo $_SESSION['city2']; ?>">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
<div style="display:none"><iframe name="ifr2" width="20" height="20">
<form method="post" action="http://mydomain.com/texting/register.php?list_id=15">
<input type="hidden" name="name" value="<?php echo $_SESSION['name2']; ?>" />
<input type="hidden" name="email" value="<?php echo $_SESSION['email2']; ?>" />
<input type="hidden" name="ok" value="1" />
<input type="submit" id="submit" value="Sign Up" style="visibility:hidden;" />
</form></iframe>
</div>
but it is not working, any suggestion to make it happen, the same data is to be sent to both the urls automatically using javascript
You can use jQuerys ajax and send the data with post, to both the urls.
first save all data you want to send in an valid data array. if you want it automated, you can do something like this:
var sendData = {};
$("#formId").find("input").each(function(i, item){
sendData[item.name] = item.value;
});
or as a simple string:
var sendData = "name=value&email=value";
then send the form data to both urls with ajax, as post type:
$.ajax({ url: "http://url1/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
$.ajax({ url: "http://url2/", type: "POST", data: sendData,
success: function(response){
alert(response);
}
});
Note: make sure to return false to the button or sending form, you can do that something like:
$("formId").submit(function(){
// do ajax send data
return false;
}
EDIT: added unchecked code for this, with comments
$(document).ready(function(){
// grab the form and bind the submit event
$("#formId").submit(function(){
// collect all the data you want to post
var sendData = {};
this.find("input").each(function(i, item){
sendData[item.name] = item.value;
});
// send the request to both urls with ajax
$.ajax({ url: "url1", type: "POST", data: sendData,
success: function(response){
// handle response from url1
alert(response);
}
});
$.ajax({ url: "url2", type: "POST", data: sendData,
success: function(response){
// handle response from url2
alert(response);
}
});
// return false, to disable default submit event
return false;
});
});
just send name and email to the server script in a regular form,
then do two requests from within your register.php with something like HttpRequest or the like...
some freehand code:
client:
<form id="autoSubmitForm" method="post" action="/register.php?list_id=15">
<input type="hidden" name="name" value="<?php data['name2']; ?>" />
<input type="hidden" name="email" value="<?php data['email2']; ?>" />
<input type="submit" name="submit" value="Sign Up" style="visibility:hidden;" />
</form>
<script>
$(document).ready(function(){
$('#autoSubmitForm').submit();
});
</script>
server:
<?php
$name = $_POST["name2"];
$email = $_POST["email2"];
$url1 = 'http://lala'; //or relative to server root: '/lala'
$url2 = 'http://other';
sendRequest($url1, $name, $email);
sendRequest($url2, $name, $email);
?>
The implementation of sendRequest is worth another question (or reading the documentation of HttpRequest mentioned above)
Good luck, I see your duplicate question got closed...

Categories