get JSON from PHP with JQUERY - javascript

I have a html form in my index.php
I have my connection.php who receive the login and the password... check it into the database... and return true if the user is auth or false if not..
I return this into a json format with json_encode(array('result' => 1));
but when I try to display the result with my jquery, I have a blank page.
index.html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8" />
<title>Ticket v1.0 Administration</title>
<meta name="description" content="Système de ticket par Sami Jnih" />
<meta name="keywords" content="ticket" />
<meta name="author" content="Sami Jnih" />
<!-- <link rel="shortcut icon" href="../favicon.ico"> -->
<link rel="stylesheet" type="text/css" href="skins/css/form.css" />
<link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow" rel="stylesheet" type="text/css" />
</head>
<body id="index">
<div class="container">
<section class="main_login">
<form id="connection" class="form_login" name="form1" action="connection.php" method="POST">
<h1><span class="log-in">Connexion</span> ou <span class="sign-up">inscription</span></h1>
<p class="float">
<label for="login"><i class="icon-user"></i>Login</label>
<input type="text" id="login" name="login" placeholder="Login" required="required" />
</p>
<p class="float">
<label for="password"><i class="icon-lock"></i>Mot de passe</label>
<input type="password" id="password" name="password" placeholder="Password" class="showpassword" required="required" />
</p>
<p class="clearfix">
Inscription
<input id="submit" type="submit" value="Connexion"/>
</p>
<br />
<p id="auth"></p>
</form>​​
</section>
</div>
<footer>
<script src="js/modernizr.custom.63321.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.login.js"></script>
<script type="text/javascript" src="js/login.js"></script>
</footer>
</body>
</html>
jquery file:
$("#connection").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(json){
if (json.auth === 1)
{
$("#auth").css({
fontSize: '15px',
color: 'green'
}).text('Connexion réussi, redirection en cours..').show().fadeOut(3000);
window.location.replace("http://sami.fr/admin/contents/home/index.php");
}
else
{
$("#auth").css({
fontSize: '15px',
color: 'red'
}).text('Erreur, identifiants incorrects!').show().fadeOut(6000);
}
},
error: function(jqXHR, error){
$("#auth").text('Erreur : ');
$("#auth").after('<p>' + jqXHR.responseText + '</p>');
$("#auth").after('<p>' + error + '</p>');
}
});
});
connection.php
$rootPath = '';
require_once ($rootPath . 'application.php');
session_id(generateID($_REQUEST));
session($_REQUEST['login']);
if ( $user = authUserAccess($_REQUEST) )
{
if ( !fetchSession(session_id()) && !checkSession(session_id()) )
addSession($user, session_id());
else
updateSession($user, session_id());
$result = array('auth' => 1);
echo json_encode($result);
}
else
{
closeSession();
$result = array('auth' => 0);
echo json_encode($result);
}
Now All is working!
Thanks!

Do not use return in your php file, you need to actually output the data, via echo (with the correct header):
if ( $user = authUserAccess($_REQUEST) )
{
if ( !fetchSession(session_id()) && !checkSession(session_id()) )
addSession($user, session_id());
else
updateSession($user, session_id());
$result = json_encode(array('return' => 1));
header('Content-Type: application/json');
echo $result;
// header('Location: ' . $adminContentPath . 'home/index.php?sid=' . session_id());
}
else
{
closeSession();
header('Content-Type: application/json');
echo json_encode(array('return' => 0));
}
Also, as noted by pmandell, your callback has inconsistent names for the returned data
Lastly, you must stop the form from submitting normally else the user will get redirected:
$('#connection').submit(function(ev){
ev.preventDefault();
$.ajax({ ...

In your code:
success: function(json){
alert(data);
if ( data == 0 )
$("#resultat").html("<p>Vous êtes connecté.</p>");
else
$("#resultat").html("<p>Erreur, login ou mot de passe incorrect.</p>");
}
You are attempting to reference data which is not defined.
data is frequently what jQuery developers name the .ajax() success parameter. You can name it whatever you want. You could change your code to:
success: function(data) {
...
}
Also, the parameter of the success callback will be the JSON that the AJAX request responds with. In this case, it is an object with one attribute, response. You will need to check the value of response with:
if ( data.response === 0 ) {
$("#resultat").html("<p>Vous êtes connecté.</p>");
...
}

Related

can't send messages and $username isn't displayed

I made a chat service in php. When you get to the chat, it says "Welcome, --Username--." My problem is I added a login field, now I can't send messages and the username isn't displayed. I've looked everywhere but it seems since my code is so "unique", nothing seems to be helping. --i didn't make this all on my own, I used someone else's code for the login and someone's code for the service itself.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
if($username === 'admon' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: login.php"); //Redirect the user
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>English Pricks</title>
<meta name="description" content="A Group Chat." />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>&period; Image Dump&period;&period;&period;</p>
<p>Emoji's → </p>
<button id="emoji-button" style="border: none;">😀</button>
<p class="logout"><a id="exit" href="#">Leave</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
<input name="submitmsg" type="submit" id="submitmsg" value="↑" />
</form>
</div>
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="emoji.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var picker = new EmojiButton();
var button = document.querySelector('#emoji-button');
button.addEventListener('click', function () {
picker.showPicker(button);
picker.on('emoji', emoji => {
document.querySelector('#usermsg').value += emoji;
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
$.post("post.php", {text: clientmsg});
$("#usermsg").val("");
}else{
}
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 1000);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
In login.php file else was missing in if blocks and in order to see username you should add it to $_SESSION in the same way as you did with
$_SESSION['login'], cause i don't see anything else which can serve as temp storage in provided code. Another issue is that you placed header() function with login and password check right inside html code. This will trigger warning on a runtime that headers were already sent. In order to avoid that place your checking code in the top of the file and also check if there are no spaces before or after <?php php opening tag.
Example of fixed login.php file you can find below.
<?php
session_start();
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username);
header('Location:admin.php');
die();
}
if(isset($_SESSION['login'])) {
header('Location:admin.php'); die();
}
if(isset($_POST['submit'])) {
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
redirectWithData($username);
} elseif($username === 'admon' && $password === 'password'){
redirectWithData($username);
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
On admin page you can then display username
Welcome, <b><?php echo $_SESSION['username']; ?>
Regarding admin.php functionality. Logic for adding messages according to JavaScript code located in post.php file.
$.post("post.php", {text: clientmsg});
So, why its adding or not adding it is hard to answer for obvious reasons )
And btw, in your logout logic in admin.php file change
window.location = "index.php?logout=true"; -> window.location = "?logout=true"; it will fallback to the same page on which you already have redirect logic.

save text fields into MySQL database

#Edit 2,
I think the problem stems from passing arguments.
<br />
<b>Warning</b>: mysqli_connect(): (HY000/2002): Connection refused in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>12</b><br />
Failed to connect to MySQL: Connection refused<br />
<b>Warning</b>: mysqli_query() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>30</b><br />
<br />
<b>Warning</b>: mysqli_close() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>41</b><br />
#Edit, if I disable doRecord method and assign a random number to $retVal, I can see its value from the console. I think the problem is about the function’s body.
I’m trying to save information which is put by the fields into MySQL database. But I cannot see even what the result is by exit(json_encode(array("response" => $response))); or exit(json_encode(array("response" => "not entered")));. I’m sure database works, I tested. Also, button onclick works, but no more. What’s the wrong?
saveEmail.php
<?php
function doRecord($host, $username, $password, $dbName,
$senderName, $senderMail, $senderSubject, $senderBody, $cronInput) {
$retVal = 0;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = new mysqli($host, $username, $password, $dbName);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$date = gmdate('Y-m-d h:i:s', time());
/*$htmlBody =
"bodyy <p>link burada </p>
<p> </p>
<p>fdgfd</p>";
*/
// Attempt insert query execution
$sql = "INSERT INTO staj.info(name, email, subject, body, progressTime, cronInput)
VALUES
('$senderName', '$senderMail', '$senderSubject', '$senderBody', '$date', '$cronInput');";
if(mysqli_query($link, $sql)){
//echo "Records inserted successfully.";
$retVal = 1;
} else{
//echo "\n\nERROR: Could not able to execute $sql. " . mysqli_error($link);
$retVal = 0;
}
// Close connection
mysqli_close($link);
return $retVal;
}
if (isset($_POST['cron'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
$cron = $_POST['cron'];
$retVal = doRecord("127.0.0.1", "root", "12345678", "staj",
$name, $email, $subject, $body, $cron);
if ($retVal == 1) {
$response = "Mail is put into database";
} else {
$response = "SQL error.";
}
exit(json_encode(array("response" => $response)));
} else {
exit(json_encode(array("response" => "not entered")));
}
?>
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.css" rel="stylesheet">
<style type="text/css">
textarea, input {
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3">
<label for="name">Name:</label>
<input id="name" placeholder="Name" class="form-control" required>
<label for="email">E-mail:</label>
<input id="email" placeholder="E-mail" class="form-control" required>
<label for="subject">Subject:</label>
<input id="subject" placeholder="Name" class="form-control" required>
<!--<label for="body">Body:</label>-->
<textarea id="summernote" placeholder="Email body" name="editordata"></textarea>
<label for="cron">Crontab:</label>
<input id="cron" placeholder="CronTab Input" class="form-control">
<input type="button" onclick="saveMail()" value="Save it to Database" class="btn btn-success btn-info">
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script type="text/javascript">
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else {
caller.css('border', '');
return true;
}
}
function saveMail() {
console.log("SaVinG Attempt...");
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#summernote");
var cron = $("#cron");
if (isNotEmpty(cron)) {
$.ajax({
url: 'saveEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
cron: cron.val()
}, success: function (response) {
console.log(response);
}
});
}
}
</script>
<!-- WYSIWYG editor jses -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.js"></script>
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
focus: true
});
});
</script>
</body>
</html>
It seems like you have an incorrect quotation mark in your saveEmail.php file. If you use code highlighting, it's easier to see. Instead of:
exit(json_encode(array("response" => "not entered”)));
Try:
exit(json_encode(array("response" => "not entered")));
EDIT:
To see what kind of error blocks your AJAX call, put these lines of call at the beginning of saveEmail.php:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Then temporarily change your ajax call to look like this:
$.ajax({
url: 'saveEmail.php',
method: 'POST',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
cron: cron.val()
}, success: function (response) {
console.log(response);
} });

jquery form validation and php script in one page

after implementing a jquery form validation and redirecting with function btn_onclick()
{ window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php my webapps php script wont be executed. The user become trough a javascript function and window.location.href from index.php redirected loginprivate.php you can see here. After the first pageload the page become loaded again with <script src="loadagain.js"></script> this works fine too.
Now the problem is that if I click the submit button the php code wont become executed, that can I see because no cookies become created, and the user become redirected to index.php.
my php code:
if(isset($_POST["submit"]))
{
$hostname='localhost';
$username='root';
$password='';
unset($_POST['password']);
$salt = '';
for ($i = 0; $i < 22; $i++) {
$salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1);
}
$_POST['password'] = crypt($_POST['password'],'$2a$10$'.$salt);
$new = 0;
try {
$dbh = new PDO("mysql:host=$hostname;dbname=search",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (username, password)
VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully";
}
else{
echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0)
{
$t = time() + 60 * 60 * 24 * 1000;
setcookie("username", $_POST['username'], $t);
setcookie("userid", $new , $t);
}
else
{
}
}
my html code:
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" href="themes/my-costum-theme.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<!-- Einstellungen zur Defintion als WebApp -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="loadagain.js"></script>
<script>
$(document).ready(function () {
$('#myform').ajaxForm();
$('#myform').validate({ // initialize the plugin
rules: {
username: {
required: true,
minlength: 2,
maxlength: 30
},
password: {
required: true,
minlength: 3,
maxlength: 30
}
},
submitHandler: function (form) { // for demo
$.ajax({
type: 'post',
url: 'loginprivate.php' //url where you want to post the stuff.
data:{
username: 'root',
password: 'maxicora123'
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
window.location.href = "http://localhost/loc/main.php";
}
});
return false; // for demo
}
});
});
</script>
</head>
<body>
<div class="ui-page" data-theme="b" data-role="page">
<div data-role="header"><h1>localcorps</h1></div>
<div id="wrapper1" style=" width: 90%; padding-right:5%; padding-left:5%" name="wrapper1">
<form name="login-form" id="myform" class="login-form" action="./loginprivate.php" method="post">
<div class="header1"></div>
<div class="content1">
<div data-role="fieldcontain">
<label for="username">Username:</label>
<input name="username" type="text" class="input username" id="username"/>
</div>
</div>
<div data-role="fieldcontain">
<label for="password">Password:</label>
<input name="password" type="password" class="input password" id="password"/>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button"/>
</div>
</form>
</div>
</div>
</div>
</body>
According to your comment, I get now only this "Array ( )" on my screen. it means that you ain't posting anything to PHP page.
That's just because, you're redirecting the control to PHP page instead of submitting the form.
so, you can validate the code using jQuery and on successful validation do a ajax post request instead of shifting the control.window.location.href = "http://localhost/lak/main.php";
instead of shifting control, do a post.
$.ajax({
type: 'post',
url: 'loginprivate.php' //url where you want to post the stuff.
data:{
username: 'someUserName',
password: 'xxxxxxxxxxxx'
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
//and if you're logged in successfully, redirect here now.
}
});
Hope this will help.

upon data retrieval, form populates and then clears

I have a weird problem. I have a form that populates with a button click event. This all works fine, except that once the form populates, it clears itself. Even Firebug gets cleared. I have stripped everything down to its most basic level, and cannot figure out what the issue is.
HTML:
<?php
require_once('../hyperlink.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Shipment Assignment</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<link rel="stylesheet" href="book.css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<link rel="stylesheet" href="../css/tabletheme/style.css" type="text/css" id="" media="print, projection, screen" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>
<script type="text/javascript" src="../barcode/jquery-barcode.js"></script>
<script type="text/javascript" src="../js/tablesorter.min.js"></script>
<script src="book.js"></script>
</head>
<body>
<div id="header">
<?php display_user_hyperlinks(); ?>
<?php include ('../version.php'); ?> | Tip: Shipping Info</p>
</div>
<form>
<fieldset>
<legend>Shipping Assignments</legend>
Enter the PO that you would like to review: <input id="po"/><input type="submit" id="getPo" value="Retrieve"/>
</fieldset></form>
<form id="result">
<div id="hide">
<div id="cl" class="width border">
CL<input id="cl"/>
</div>
<div id="recv" class="width border">
REC<input id="rec"/>
</div>
<div id="pricePd" class="width border">
<input id="price" placeholder="Price Paid"/>
</div>
<div id="box" class="border">
<input id="title" style="width: 445px;" placeholder="Title"/><br>
<input id="isbn10" style="width: 445px;" placeholder="ISBN10"/><br>
<input id="isbn13" style="width: 445px;" placeholder="ISBN13"/><br>
</div>
</div></form>
<div id="remain"class="border">
Qty Rem: <input type="text" id="qtyRem"/>
</div>
</body>
</html>
book.js
$(document).ready(function() {
$("#getPo").click(function() {
$.ajax ({
type: "POST",
url: "poInfo.php",
async:false,
dataType: "json",
data: ({po: $('#po').val()}),
success: function(data){
console.log(data);
$("#isbn13").val(data.isbn);
$("#isbn10").val(data.isbn10);
$("#title").val(data.title);
}
}); //END OF AJAX
}); // END OF GETPO FUNCTION
});
poInfo.php:
<?php
ini_set('display_errors',"1");
require_once ('../db.php');
$conn = db_connect();
$i=0;
$po = 'JJD090969';
$result = $conn->query("select * from ship_assign where po = '$po'");
while ($row = $result->fetch_assoc()) {
$isbn10 = $row['isbn10'];
$isbn = $row['isbn13'];
$azLow = $row['azLow'];
$buyback101 = $row['Buyback101'];
$textRecycle = $row['textBookRecycle'];
$textRush = $row['textBookRush'];
$bookStores = $row['bookStores'];
$textBooks = $row['textBooks'];
$bookJingle = $row['bookJingle'];
$cash4Books = $row['cash4Books'];
$bookbyte = $row['bookbyte'];
$sellBack = $row['sellBack'];
$cheggBs = $row['chegg'];
$valore = $row['valore'];
$powell = $row['powell'];
$amzBuyBack = $row['amazonBuyBack'];
$collegeBooksDir = $row['collegeBooksDirect'];
$result2 = $conn->query("select title from book where isbn13 = '$isbn'");
$row1 = $result2->fetch_assoc();
$title = $row1['title'];
} //END OF WHILE STATEMENT
$guides= array('isbn10'=>$isbn10,'isbn'=>$isbn,'title'=>$title);
$conn->close();
echo json_encode($guides);
?>
Everything works as it should, except that the form clears once populated. I am hard coding in the po that I want to use instead of having to type it in every time, but the result is the same either way. Any ideas on how to fix this??
Try this:
$(document).ready(function() {
$("#getPo").click(function(event) {
event.preventDefault();
$.ajax ({
type: "POST",
url: "poInfo.php",
// async:false, deprecated
dataType: "json",
data: ({po: $('#po').val()}),
success: function(data){
console.log(data);
$("#isbn13").val(data.isbn);
$("#isbn10").val(data.isbn10);
$("#title").val(data.title);
}
}); //END OF AJAX
}); // END OF GETPO FUNCTION
});

ajax code200 error can't connect to the url

I am using ajax to run a test id, but it does not work with code: 200 error.
And since ajax is not returning a value, it keeps getting error and prints "failed"
The id of add_user.html is checked in real time through the ajax of id_check.js.
However, memid_check.php, which sends data from id_check.js, does not seem to run.
to confirm
memid_check.php
echo "<script> alert('test!!!'); </script>";
.....
But did not run.
All files are in one folder, so the path seems to be fine
id_check.js
$(function(){
var id = $('.id_tbox');
var pwd =$('.pwd_tbox');
var name =$('.name_tbox');
var email =$('.email_tbox');
var idCheck = $('.idCheck');
$(".memcheck_button").click(function(){
console.log(id.val());
$.ajax({
type: 'post',
dataType: 'json',
url: "memid_check.php",
data:{id:id.val()},
success: function(json){
if(json.res == 'good'){
console.log(json.res);
alert("사용가능한 아이디");
idCheck.val('1');
}
else{
alert("다른 아이디 입력");
id.focus();
}
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
console.log("failed");
}
});
});
});
memid_check.php
<?php
echo "<script> alert('test!!!'); </script>";
include "db_c.php";
$id = $_POST['id'];
$sql = "SELECT * FROM add_user WHERE id = '{$id}'";
$res = $database -> query($sql);
if( res->num_rows >= 1){
echo json_encode(array('res'=>'bad'));
}
else{
echo json_encode(array('res'=>'good'));
}
?>
add_user.html
<?php
include "database.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=medium-dpi">
<link rel="stylesheet" href="add_user_style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/default.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cinzel|Permanent+Marker|Rajdhani&display=swap" rel="stylesheet">
<script type="text/javascript" src="id_check.js"></script>
</head>
<body>
<div class="aus_portrait"></div>
<div class ="aus_form" align ="center">
<div class="aus_box">Sign Up</div>
<form action="loginP.php" method="post">
<p class = "id">ID</p><input type="text" name="id" class="id_tbox">
<p class = "pwd">PASSWORD</p><input type="text" name="pwd" class="pwd_tbox">
<p class = "name">MAIL</p><input type="text" name="email" class="email_tbox">
<p class = "email">NAME</p><input type="text" name="name" class="name_tbox">
<input type="submit" class="sub_button" value="Submit">
<input type="button" class="exit_button" value="Cancel">
<input type="hidden" name="idCheck" class="idCheck">
<div class="memcheck_button">중복확인</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() { $(".exit_button").on("click", function(){ location.href="login.html"});}); </script>

Categories