AJAX can't connect with sql database - ajax

I try to create a form that will check if the user exist in database but i'm having problem connecting AJAX with sql, if you can help me finding out this problem i would be very appreciated, sorry my english is not great. these are my code:
<!DOCTTYPE html>
<html lang="en">
<head>
<mete charset="UTF-8">
<title>Email client</title>
<script type="text/javascript">
function load(){
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'checkuser.php', true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="loginform" onclick="load();">
Username : <input name="userID" type="text" id="userID"><br />
Password : <input name="password" type="password" id="passWD"><br />
<input type="submit" id="button" value="Get in there"> <br />
<p>Don't have an account? please register </p>
</form>
<div id="info"></div>
</body>
</html>
my php (checkuser.php):
<?php
$dbhost = 'localhost';
$dbuser = 'xxxx';
$dbpass = 'xxxx';
$dbname = 'xxxx';
$dbtable = 'xxxx';
$q=$_GET["userID"];
$p=$_GET["passWD"];
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$dbselect = mysql_select_db($dbname,$con);
$sql="SELECT * FROM $dbtable WHERE userID='$q'";
$result = mysql_query($sql);
if (mysql_num_rows($result)==0) {
echo "not registered";
} else {
while($row = mysql_fetch_array($result))
{
if (($row['passWD'])==$p) {
echo "registered";
} else { echo "not registered";}
}
}
mysql_close($con);
?>

Your PHP expects to have two query string parameters passed to it (don't send passwords in query strings, they might get logged, use a POST request) but your JavaScript is just requesting the URL of the script without any query string at all.
Presumably you want to extend load to get data from the form, and to call load in the submit event for the form and not the load event of the document.

Related

Am trying to upload image using ajax php and jquery what am i doing wrong here

$(document).ready(function(){
$("#log").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var img = $("#img").val();
$.ajax({
url:"ajax.php",
type:"POST",
async:false,
data:{
"postD" :1,
"nameD" : name,
"emailD" : email,
"imgD" : img
},
success:function(data){
$("#name").val('');
$("#email").val('');
$("#img").val('');
}
});
});
});
function displaydata(){
$.ajax({
url:"ajax.php",
type:"POST",
async:false,
data:{
"displayP":1
},
success:function(data){
$("#datafromDb").html(data);
}
});
}
<?php
include("db.php");
$sql = "
CREATE TABLE IF NOT EXISTS temptable (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(20) NOT NULL,
PRIMARY KEY(id)
);
";
mysqli_query($connect, $sql);
if (isset($_POST['postD'])){
if(!empty($_POST['nameD']) && !empty($_POST['emailD'])&& !empty($_FILES['imgD'])) {
$emailP = $_POST['emailD'];
$nameP = $_POST['nameD'];
$imgP = $_FILES['imgD']['name'];
$tmpname = $_FILES['imgD']['tmp_name'];
$folder = "upload/";
move_uploaded_file($tmpname, $folder.$imgP);
$insert = "INSERT INTO `inserteddata` (`name`, `email`,`img`)
VALUES('{$nameP}','{$emailP}','{$imgP}')";
$qry = mysqli_query($connect, $insert);
if($qry) {
echo "inserted";
}
}else {
echo "make sure all fields are filled";
}
}
if(isset($_POST['displayP'])){
$sel = "SELECT * FROM `inserteddata`";
$res = mysqli_query($connect, $sel);
while($row=mysqli_fetch_array($res)) {
echo "Name = ".$row['name']."<br><br><br>";
}
}
?>
<?php
$connect = mysqli_connect("localhost", "root", "", "ajaxinsert");
if(!$connect) {
echo "database connection error".mysqli_error();
}else {
echo "connected successfuly<br><br><br>";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ajax insert</title>
<script type="text/javascript" src="jquery-3.2.1.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<div id="datafromDb">
<script type="text/javascript">
document.write(displaydata());
</script>
</div>
<br>
<br>
<form enctype="multipart/form-data" action="" method="post">
<input type="text" id="name"><br><br>
<input type="email" id="email"><br><br>
<input type="file" id="img" name="img"><br><br>
<input type="submit" value="Login" >
<a href="" id="log" >add</a>
</body>
</html>
Am trying to upload image using ajax php and jquery what am i doing wrong here. the image should be uploaded without refreshing the page. i have tried the above code. if your see any prolem, help!!
The thing is i want to move the uploaded file to the upload folder and insert the image name to the database as a BLOB.
You can use FormData objects but you need to write the code in plain Javascript because I think JQuery doesn't support it yet. Please read this for more information https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Onchange() for AJAX

I am trying to display the onchange value of a textbox using ajax. My code is as follows :
ajaxquery.php
<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
//fuction to return the xml http object
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">
<form style="text-align:center" method="post" action="" name="form1">
<p>Country : <input type="text" name="country" onChange="getCurrencyCode('code.php?country='+this.value)">
</form>
</body>
</html>
code.php
<?php
$country=$_REQUEST['country'];
echo $country;
?>
The value is not displaying. Where am I going wrong?
P.s. I am completely new to ajax and have no knowledge about it. Appreciate any help :)
<p>Country : <input type="text" name="country" onblur="getCurrencyCode('code.php?country='+this.value)">
<p>Country Code : <input type="text" name="cur_code" id='cur_code' ">
Changed the onchange function to onblur and added another input type. It is working perfectly now!

How to Save File with time as name and return time value with uploadify

what i intend to do, is to use uploadify to upload a file, change its name in uploadify.php for the value of time() ,save it , and return the name of the saved file back to the HTML, im not sure how to do it, currently im using this as guide
http://www.uploadify.com/documentation/uploadify/customizing-the-server-side-upload-script/
and this is my code so far
index.php
'<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"></script>
<script src="jquery.uploadify.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="uploadify.css">
<style type="text/css">
body {
font: 13px Arial, Helvetica, Sans-serif;
}
</style>
</head>
<body>
<form>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>',
'name' : 'somename'
},
'method' : 'post',
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php',
onUploadComplete : function(data, file , response){
alert('The file was saved to: ' + data);
alert(response);
}
});
});
$(document).ready(function() {
$("#FormSubmit").click(function (e) {
var img = 'localhost/uploads/'+ $("#hidden").val;
var cuenta_sap = $("#cuenta_sap").val();
var ubicacion = $("#ubicacion").val();
var codigo_centro_beneficio = $("#codigo_centro_beneficio").val();
var nombre = $("#nombre").val();
var proyecto = $ ("#proyecto").val();
var departamento = $ ("#departamento").val();
var tipo_activo = $("#tipo_activo").val();
var proveedor = $("#proveedor").val();
var modelo = $("#modelo").val();
var numero_serie = $("#numero_serie").val();
var marca = $ ("#marca").val();
var numero_remision = $("#numero_remision").val();
var myData ='cuenta_sap='+ cuenta_sap + '&ubicacion='+ ubicacion +
'&codigo_centro_beneficio='+ codigo_centro_beneficio + '&nombre=' + nombre + '&proyecto='
+ proyecto + '&departamento='+ departamento + '&tipo_activo=' + tipo_activo
+'&proveedor='+ proveedor +'&modelo=' + modelo + '&numero_serie=' + numero_serie +'&marca='
+ marca + '&numero_remision='+ numero_remision;
e.preventDefault();
if(cuenta_sap==''||ubicacion==''||codigo_centro_beneficio==''
||nombre==''||proyecto==''||departamento
==''||tipo_activo==''||proveedor==''||modelo==''
||numero_serie==''||marca==''||numero_remision=='')
{
alert("Formato incompleto!");
return false;
}
$("#FormSubmit").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //
success:function(result){
$("#responds").delay(10000).fadeIn();
$("#responds").append("<li class='res'>"+result+"</li>");
$('.res').remove();
$("#proyecto").val(''); //empty text field on successful
$("#departamento").val(''); //empty text field on successful
$("#tipo_activo").val(''); //empty text field on successful
$("#modelo").val(''); //empty text field on successful
$("#numero_serie").val(''); //empty text field on successful
$("#marca").val(''); //empty text field on successful
$("#numero_remision").val(''); //empty text field on successful
$("#cuenta_sap").val(''); //empty text field on successful
$("#ubicacion").val(''); //empty text field on successful
$("#nombre").val(''); //empty text field on successful
$("#codigo_centro_beneficio").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button
$.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut();
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
<div class="content_wrapper" id="wrapepr">
<div class="form_style">
<input name="hidden" id="hidden" type="text"></input>
<br>
<a>Datos</a>
<br>
<input name="cuenta_sap" id="cuenta_sap" placeholder="cuenta sap" class="input"></input>
<select name="departamento" class="input" id="departamento">
<option value = "">seleccione departamento</option>
<?php
include("db.php");
$stmt = $db->prepare("SELECT `id`, `departamento` FROM `departamentos`");
$stmt->execute();
$stmt->bind_result($id,$departamento);
while ($stmt->fetch()){
echo "<option value='$id'>$departamento</option>";
}
?>
</select>
<select name="proyecto" class="input" id="proyecto" >
<option value = "" >seleccione proyecto</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`proyecto` FROM `proyectos`");
$stmt->execute();
$stmt->bind_result($id,$proyecto);
while ($stmt->fetch()){
echo "<option value='$id'>$proyecto</option>";
}
?>
</select>
<select name="tipo" class="input" id="tipo_activo">
<option value = "" class="input" >tipo de activo</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`tipo` FROM `tipo_activo`");
$stmt->execute();
$stmt->bind_result($id,$tipo_activo);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$tipo_activo</option>";
}
?>
</select>
<select name="proveedor" class="input" id="proveedor">
<option value = "" class="input" >seleccione proveedor</option>
<?php
$stmt = $db->prepare("SELECT `id` ,`nombre` FROM `proveedores`");
$stmt->execute();
$stmt->bind_result($id,$nombre);
while ($stmt->fetch()){
echo "<option value='$id' class='input'>$nombre</option>";
}
?>
</select>
<input name="codigo_centro_beneficio" id="codigo_centro_beneficio" placeholder="codigo centro
beneficio" class="input"></input>
<input name="nombre" id="nombre" placeholder="nombre" class="input"></input>
<input name="modelo" id="modelo" placeholder="modelo" class="input"></input>
<input name="numero_serie" id="numero_serie" placeholder="numero_serie" class="input">
</input>
<input name="marca" id="marca" placeholder="marca" class="input"></input>
<input name="numero_remision" id="numero_remision" placeholder="numero remision" class="input">
</input>
<input name="upload" id="upload" class="input" type="file"></input>
<button id="FormSubmit">registrar</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
<ul id="responds" >
</ul>
</div>
</body>
</html>'
and uploadify.php
'
$targetFolder = '/uploads'; // Relative to the root
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$now = time();
$name = $_POST('name')FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
if(file_exists($targetFile)){
++$now;
$targetFile = rtrim($targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
$name $targetPath,'/') . '/' . $now .'.'. $fileParts['extension'];
echo $name;
}
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
}
else {
echo 'Invalid file type.';
}
?>'
I found the answer to this, after a while of searching and reading uploadify manuals, it turns out if you use onUploadComplete, and you just upload one single fine, the method will never excecute, and it will keep waiting for more files, instead for one file only, you have to use onUploadSuccess, and read the data returned by it using file,data,response as parameters.

Adding form data to mysql database PHP and AJAX

I am wanting to have a form that will let me add names to my database without refreshing the form. I have been working on it but it does not seem to work. I am quite new at this so any help is appreciated.
For my index.html I have:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#firstname").val();
var username = $("#lastname").val();
var dataString = 'firstname='+ firstname + 'lastname=' + lastname
if(firstname=='' || lastname=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<body>
<form method="post" name="form">
<ul><li>
<input id="firstname" name="firstname" type="text" />
</li><li>
<input id="lastname" name="lastname" type="text" />
</li></ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div></form>
For join.php:
<?php
include("db.php");
if($_POST)
{
$firstname=$_POST['firstname'];
$lastname=$_POST['username'];
mysql_query("INSERT INTO persons (firstname,lastname) VALUES('$firstname','$lastname')");
}
?>
and db.php:
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "test";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
?>
there is mistake in code,
you have coded
var name = $("#firstname").val();
var username = $("#lastname").val();
var dataString = 'firstname='+ firstname + 'lastname=' + lastname
you have to used the variables name and username in dataString but you have written the id(s) of fields for first and last name. change either the variable name or variables used in dataString
corrected line is :
var dataString = 'firstname='+ name + 'lastname=' + username
And
$lastname=$_POST['username']; => $lastname=$_POST['lastname'];

Ajax ready state not stuck on 1

after searching the internet I was unable to find an answer as to why my AJAX code is not working. My assignment is to retrieve a text file and display it to the browser using AJAX but the ready state stops at 1. an example file is canada.txt and is located in the directory http://157.201.194.254/~ercanbracks. The .html and .js files are below:
HTML file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>AJAX</title>
<link rel="stylesheet" type="text/css" href="assign09.css" />
<script type="text/javascript" src="assign09.js"></script>
</head>
<body>
<h1>Ten Largest Cities</h1>
<h3>Select a Country:</h3>
<form action="">
<select id="country">
<option value="canada">Canada</option>
<option value="mexico">Mexico</option>
<option value="russia">Russia</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit"
onclick="makeRequest(document.getElementById('country').value)" />
<div id="error"> </div>
</form>
<h3>Cities:</h3>
<div id="cities">
<pre>
City Population
------------------ ---------------
<span id="cityList"></span>
</pre>
</div>
</body>
</html>
.js file:
var httpRequest;
var countryOption;
function makeRequest(option)
{
countryOption = option;
if (window.XMLHttpRequest) // Modern Browsers
{
httpRequest = new XMLHttpRequest();
}
else // older IE browsers
{
try
{
httpRequest = new ActiveXObject("Msxm12.XMLHTTP");
}
catch (e)
{
try
{
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert('ERROR - Unable to make XMLHttpRequest');
}
}
}
if (!httpRequest)
{
alert('ERROR: httpRequest failed -- try a different browser');
return false;
}
else
{
var url = "http://157.201.194.254/~ercanbracks/" + option + ".txt";
alert('Ready State = ' + httpRequest.readyState);
httpRequest.onreadystatechange = getCities;
httpRequest.open("GET", url, true)
httpRequest.send(null);
}
}
function getCities()
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.readyState == 4)
{
alert('Ready State = ' + httpRequest.readyState);
if (httpRequest.status == 200)
{
var response = httpRequest.responseText;
document.getElementById("cities").innerHTML = response;
}
else
{
alert('problem with request');
alert('Ready State = ' + httpRequest.statusText);
}
}
}

Resources