AJAX success function works, but file isn't running - javascript

I'm new to StackOverflow, web development, and I'm low on time for this assignment, so I apologize if I'm a bit slower at understanding web development vocabulary and any answers or tips. I'm having trouble with calling another php file through ajax.
index.php:
<!--------------------------- HTML STARTUP ----------------------------------->
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="finalproject.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="finalproject.js"></script>
<title>Final Project</title>
</head>
<body>
<!--------------------------- LOGIN ------------------------------------------>
<?php
require_once 'dbconnection.php';
//----------------------- CREATE USERS TABLE -----------------------------------
$userspass = "CREATE TABLE usersPass (
userID VARCHAR(60),
password VARCHAR(60)
);";
$connected->query($userspass);
$selectAllInfo = "SELECT * FROM usersPass;";
$connected->query($selectAllInfo);
//-------------------------- LOG IN OR REGISTER --------------------------------
?>
<form id="trial"><button onclick="OpenRegister()">Sign Up!</button>
<script>
$(document).on("click" , "#Register", function(e)
{
var datastring = $("#trial").serialize();
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: datastring,
success: function(data){
alert('Sign Up function is a success!');
}
});
e.preventDefault();
});
</script></form>
<br/><br/>
<button onclick="InputInfo()">Login</button>
<?php
$connected->close();
?>
</body>
</html>
And here's the JavaScript when the function is called.
finalproject.js:
/*jslint browser: true*/
/*global $, jQuery, alert*/
function OpenRegister() {
'use strict';
$('form').append("<div id=SignInContainer>
<span style='font-size: 20px'>UserID</span>
<input type='text' name='UserID' value='Type userID here...'>
<span style='font-size: 20px'>Password</span>
<input type='text' name='UserID' value='Type password here...'>
<button id='Register'>Submit</button>
</div>");
}
$(document).ready(function () {
'use strict';
$(document).on('focus', 'input', function () {
$('input').focus(function () {
$(this).val('');
});
});
});
And this is the php file I'm trying to load. userlogin.php:
<?php echo "If this displays, you win." ?>
dbconnection.php
<?php
$connected = new mysqli('localhost', 'Username', 'Password', 'Username');
mysqli_select_db($connected, 'cferna50');
// Check connection
if ($connected->connect_error) {
die("Connection failed: " . $connected->connect_error);
}
I'm just trying to get the "userlogin.php"file to run through AJAX. I'm running this thing on Chrome. I've heard that there is a bit of a problem with using AJAX on local files, but I tried that --access-file-from-files thing and it didn't help. I tried running it on FireFox and Internet Explorer and it still doesn't help. I'm sure I have everything in the same directory. I'm using an online school server thing to do all this. I've been hurting my head over this for endless hours, any help would GREATLY be appreciated.

Simply because you are not passing (data) through the method, either you Serialize the data or pass them individually, and i suppose you will use the first method to save time
<script>
$(document).on("submit","#loginForm", function(e)
{
var datastring = $("#loginForm").serialize();
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: datastring,
success: function(data){
alert(data);
//or
//alert('Sign Up function is a success!');
},
error: function(){
alert("error handling");
}
});
e.preventDefault();
});
</script>
HTML
<form id="loginForm" method="POST">
<input type="text" name="userid" id="userid" placeholder="user ID" />
<input type="text" name="password" id="password" placeholder="Password" />
<button type="submit" >Submit</button>
</form>
PHP
<?php
if(isset($_POST['userid'])){
$username = $_POST['userid'];
$pass = $_POST['password'];
//do your magic now
}
?>

Correct concatenation of html string at .append() remove if($("#Register").click())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function SignUp() {
if ($("[name=username]").val().length
&& $("[name=password]").val().length) {
$.ajax({
type: 'POST',
url: 'userlogin.php',
data: {
username: $("[name=username]").val(),
password: $("[name=password]").val()
},
success: function(data) {
alert('Sign Up function is a success!');
},
error: function() {
alert("stacsnippets success")
}
});
}
}
</script>
<script>
function OpenRegister() {
'use strict';
$('body').append("<div id=SignInContainer>"
+ "<span style='font-size: 20px'>UserID</span>"
+ "<input type='text' name='username' placeholder='Type userID here...'>"
+ "<span style='font-size: 20px'>Password</span>"
+ "<input type='password' name='password' placeholder='Type password here...'>"
+ "<button onclick='SignUp()' id='Register'>Submit</button>"
+ "</div>");
}
</script>
<button onclick="OpenRegister()">Sign Up!</button>
php
if (isset($_POST["username"]) && isset($_POST["password"])) {
// do username, password validation stuff here
}
jsfiddle https://jsfiddle.net/qnrnn5b5/

Related

How do you save the value of a textbox on the server with php?

So I tried to save the elements in a textbox to a text file on the server by using php. I've searched for solutions but none of them worked yet. This is a snippet of my HTML and JS part:
<input type="search" id="textinput" value="" />
<script type="text/javascript">
function sendText() {
var dataset = { "value": document.getElementById('textinput').value };
console.log(dataset);
$.ajax({
url: 'sendText.php',
type: 'POST',
data: dataset,
success: function() {
alert('Success');
}
});
}
</script>
<button type="submit" id="button" onclick="sendText()">Send</button>
and this is the php:
<?php
$fp = fopen('chat.txt', 'w');
fwrite($fp, $_POST['value']);
?>
If someone could help me there I would be thankful!

Loading data from a server using jquery $.post

What im about to do is to send data to the server through a form and to a php-script. Then I want to get it back and place it in the right spot using Jquery. I don't know why, but this solution doesnt seem to work as im just getting the "No text in the textbox!". Does someone have any tips?
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#send").click(function(event) {
$.post("target.php", {
melding: $("#input").val().
}, function(data){
$("#meldinger").after("<div>" + data + "</div>");
});
event.preventDefault();
});
});
document.getElementById('demo').innerHTML = date();
</script>
<title>Meldingssystem</title>
</head>
<body>
<h1>Meldingsutveksling</h1>
<form action="target.php" method="post">
<textarea id="input" name="input" cols="40" rows="2"></textarea>
<br/><input type="submit" name="submit" value="Send">
</form>
<h2>Meldinger</h2>
<div id="meldinger">
</div>
</body>
</html>
PHP
<?php
if (!empty($_POST['input'])) {
$melding = $_POST['input'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
?>
This
if (!empty($_POST['input'])) {
$melding = $_POST['input'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
Should be
if (!empty($_POST['melding'])) {
$melding = $_POST['melding'];
echo $melding;
}
else {
echo "No text in the textbox!";
}
because there is no input POST parameter sent
first, please read https://api.jquery.com/jquery.post/
your php script expects data in the input field. but your jquery POST doesn't put anything in an input field.
instead try something like:
$.ajax({
data: {
input: $("#input").val()
},
datatype: "text",
method: "POST",
success: function(data, status, xhr) {
$("#meldinger").after("<div>" + data + "</div>");
},
error: function(xhr, status, error) {
alert("zog zog");
}
};
Notice that input is present in the data parameter.

How to pass on a form through Ajax, and PHP

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>

How to login users using ajax and php?

I've added an ajax jquery function to do a much nicer login, but it still doesn't work. What am I doing wrong? Thanks.
form_log.php withing heads:
<script type="text/javascript">
$(document).ready(function() {
$('#myform').submit(function() {
$.ajax({
type: "POST",
url: 'login.php',
data: {
username: $("#username").val(), //id
password: $("#password").val()
},
success: function(data)
{
if (data === 'Correct') {
window.location.replace('index.php');
}
else {
alert(data);
}
}
});
});
});
</script>
And the in form_log.php's html bodies:
<form id="myform">
<label for="username">Username</label>
<input type="text" id="username" value="waqmaz#gmail.com" />
<label for="password">Password</label>
<input type="text" id="password" value="Lol123" />
<input type="submit" id="login" value="Login"/>
</form>
Now login.php:
<?php
session_start();
require("funkcje_bazy.php");
//require('fff.php');
$lacz = lacz_bd();
$nazwa_uz_l = $_POST['username'];//nazwa_uz_l
$haslo_l = $_POST['password']; //haslo_l
$wynik = $lacz->query("SELECT * FROM uzytkownicy WHERE email='".$nazwa_uz_l."' AND haslo = '".$haslo_l."' AND aktywacja IS NULL ");
if($wynik->num_rows>0) {
$_SESSION['prawid_uzyt'] = $nazwa_uz_l;
echo ('Correct');
}
else
{
echo 'Incorrect username/password';
}
?>
At the top of all these 2 files I have session_start(); icluding index.php.
The login doesn't work. When I click input submit, nothing happens. I am new to an jquery ajax. I check the correct answers, thanks.
Try to prevent the default action of the submit button by using event.preventDefault(), meaning block the post back which is about to happen,
$('#myform').submit(function(e) {
e.preventDefault();
.
.
//rest of your code.
An alternative is to use:
$('#login').click(function() {

Jquery ajax() function won't load PHP script

I'm trying to create a simple login with PHP and MySQL and I'm using the AJAX() jquery function to load the PHP script.
All that I want to do is to load a new web page (for example java2s.com) when the script finds the user in my database.
Problem is that the script won't work at all.
This is the HTML with the Jquery:
EDIT: This is the fixed code thanks to all those who commented, which sadly still doesn't work.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
)
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="submit" id="loginForm" class="button positive">
</body>
</html>
The PHP script is very simple:
<?php
$data = file_get_contents('php://input');
$result = json_decode($data);
$con=mysqli_connect("localhost","****","*****","*******");
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."';";
$exists = mysqli_query($con,$str);
if (mysqli_num_rows($exists) ==1)
{
$arr = array('result'=>"login successful");
$ris=json_encode($arr);
echo $ris;
}
else
{
$arr= array('result'=>"login error");
$ris=json_encode($arr);
echo $ris;
}
mysqli_close($con)
?>
When I load the page and press the submit button nothing will happen.
Anyone can help?
Thank you very much in advance
try something like this
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: jsonlogin,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
EDITED CODE
you have not implemented DOM ready method correctly
$(document).ready(function(){
// code goes here
});
Maybe because all the php is commented out?
Also in your success function should look like this:
success: function(response){
dosomethingwithrespones(response);
}
The data in the $.ajax denotes what you send.
why are you using function ajaxJson()... try to remove it and if you really want to use it then modify your button code like this and remove $("#loginForm").click(function() { } from jquery...
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
and change <script type="text/javascript"> instead of <script language="javascript">.. this identifier is not standard, this attribute has been deprecated(outdated by newer constructs) in favor of type.
first way
function ajaxJson()
{
//your code goes here without triggering **click** event..
}
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
second way
$("#loginForm").click(function()
{
//your code goes here...
}
<input type="submit" id="loginForm" class="button positive">
keep everything outside $(document).ready function...
hope it may help you
You have missed ending { and } for ready function.try below code.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(function () {
$("#loginForm").click(function() {
alert("hi");
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
});
});
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="button" id="loginForm" class="button positive">
</body>
</html>
try this query in login.php,
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."' ";
Jquery:
$(document).ready(function(){
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
dataType: 'json',
data: sendstr,
success:function(response){
if (response.result=="login successful")
{
change();
}else{
alert(response.result);
return false;
}
}
});
});
});

Categories

Resources