AJAX PHP Database NOT WORKING no errors - php

I am new to AJAX and am trying to insert form data into a database using ajax and php. It is simply not working, I had errors to start off but now there are no more errors and the database doesn't update and there is no response text. Please Help!
AJAX
function submit(){
var vid = <?php echo $user['vid'] ?>;
var type = document.getElementById("type").value;
var rules = document.getElementById("rules").value;
var comments = document.getElementById("comments").value;
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("page").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "/content/training/request/submit.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("vid="+vid+"&type="+type+"&rules="+rules+"&comments="+comments);
}
</script>
PHP FILE AJAX IS CALLING:
<?php
require("http://".$_SERVER["HTTP_HOST"]."/config/db.php");
$stmt = $db->prepare("INSERT INTO trainingRequests (vid, type, rules, comments, timeSubmitted) VALUES (:vid,:type,:rules,:comments,:timeSubmitted)");
$stmt->bindParam(':vid', $vid);
$stmt->bindParam(':type', $type);
$stmt->bindParam(':rules', $rules);
$stmt->bindParam(':comments', $comments);
$stmt->bindParam(':timeSubmitted', $time);
$vid = $_POST["vid"];
$type = $_POST["type"];
$rules = $_POST["rules"];
$comments = $_POST["comments"];
$time = time();
$stmt->execute();
echo "Submitted!";

Don't use an HTTP URL in require. When you access the PHP script through the webserver, it runs the script (in another server instance, so it doesn't affect the current script), it doesn't return the script contents. Change it to:
require("../../config/db.php");

Related

Perform Server Side & Client Side Operations In One Project

I found an example that does exactly what I am after. My only issue is that this syntax calls a secondary file of book-suggestion.php If possible, I would like a way of performing all of this function in one page.
Here is step 1 - the client side
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
And here is part 2 - the server side
<?php
//provide your hostname, username and dbname
$host="";
$username="";
$password="";
$db_name="";
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$con=mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>
What do I need to do to combine these parts so that they are all in one file?
You could do it all one page, I use a .htaccess rewrite where everything is funneled through just one index page, so essentially doing the same thing. You just do the php above the output of your html and exit when done:
/index.php
<?php
# Create some defines
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
# Create a PDO connection, mysql_* is out of date and unsafe
# Review PDO, there are some presets to the connection that should be explored
# like emulated prepares and other such niceties
$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
# If there is a value posted, do action
if(!empty($_POST['book_name'])) {
# Bind parameters
$sql = "select book_name from book_mast where book_name LIKE ?";
$query = $con->prepare($sql);
$query->execute(array($book_name.'%'));
# Fetch normally
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo "<p>".$row['book_name']."</p>";
}
##*****THE IMPORTANT PART ******##
# Stop so you don't process the rest of the page in the ajax
exit;
}
?>
<!-- THE REST OF YOUR HTML HERE -->
<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>

How to prevent saving data when ajax response is false?

I created a text filed for customer name. Already registered customer will show while clicking that text field. Only that registered customer can entry the data. I used ajax for prevent the new user addition.
this is the ajax:
function validateForm()
{
var customerName = document.getElementById('customerName').value;
var customerId = document.getElementById('customerId').value;
var getResponse=0;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
getResponse= xmlhttp.responseText;alert(getResponse);
if(getResponse=="0")
{
return false;
}
}
};
xmlhttp.open("GET", "customer_check_ajax.php?name="+customerName+"&id="+customerId, true);
xmlhttp.send();
}
and here is the ajax page customer_check_ajax.php :
<?php
require("../../config/config.inc.php");
require("../../config/Database.class.php");
require("../../config/Application.class.php");
if($_SESSION['travelType']=='Admin')
{
$check = 1;
}
else
{
$check = '';
$logId = $_SESSION['travelId'];
$proId = $_SESSION['proId'];
$check = "proId='$proId'";
}
$cusName = $_REQUEST['name'];
$cusId = $_REQUEST['id'];
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$qry="select * FROM ".TABLE_ACCOUNTS." WHERE ID='$cusId' and accountName='$cusName' and proId='$proId'";
$res = mysqli_query($connection, $qry);//echo $qry;
$num = mysqli_num_rows($res);
if($num>0)
echo '1';
else
echo '0';
?>
here i would get the responses as 0 for new user and 1 for already registered user. But i want to stop saving data when new user addition. Please help me.
You are making Asynchronous request and the answer of the ajax will come after the function is over ..
To do what you want you must do synchronous ajax request
xmlhttp.open("GET", "customer_check_ajax.php?name="+customerName+"&id="+customerId, false); // `false` makes the request synchronous

fetching data from mysql using Ajax

I am trying to calculate the sum of prices sold between two specific dates. My query is okay but it isn't returning anything when i use in PHP. It works when i directly execute in database.
Here is my code,
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var startdate = document.getElementById('startdate').value;
var enddate = document.getElementById('enddate').value;
var queryString = "?startdate=" + startdate ;
queryString += "&enddate=" + enddate;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Start Date: <input type='date' id='startdate' /> <br />
End Date: <input type='date' id='enddate' /> <br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Here is my PHP Code
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "temp";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$startdate = $_GET['startdate'];
$enddate = $_GET['enddate'];
//build query
$query = "SELECT SUM(price) FROM ajax_example WHERE daterec >= '$startdate'";
$query .= " AND daterec <= '$enddate'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
echo "Query: " . $query . "<br />";
?>
What am i doing wrong? Thank you in advance
Satisj Rajak! you are right!
check mysql_query
first, this function will be deprecated after PHP 5.5.0, try to dont use it.
second, to get the results you have "transform" the variable in an associative array using this example code:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field_name'];
}
and if you use ajax, try to send a json format response.
hope my answer help you.
In your button click handler, try returning false. My first instinct would be that your form is being submitted by that button and your AJAX request is never being completed.
<input type='button' onclick='ajaxFunction(); return false;' value='Query MySQL'/>
If that doesn't solve it, open up google chrome and the network debugging tools. When you execute the AJAX request, check the request and response data.
In addition, you should optimize your JavaScript to be more effective.
Here is a snippet of JS which could be used in your situation:
var get = function(path) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', path);
request.onload = function() {
if (request.status == 200)
resolve(request.response);
else
reject(Error(request.statusText));
};
request.onerror = function() {
reject(Error(request.statusText));
};
request.send();
});
}
function fetchQueryResults() {
get('/test.php').then(function(response) {
var el = document.getElementById('results');
el.innerHTML = response;
}).catch(function(error) {
// Something went wrong, handle the error here
});
return false;
}

Javascript, AJAX and PHP Help

I have the following table in a MYSQL database:
Messages
MessageId (PK) int(10) - auto_inc
Message varchar(100)
I have the following PHP that echos a particular message:
<?php
//..connect to database
$query = "SELECT Message FROM Messages WHERE MessageId = '1'";
$result = mysql_query($query);
$num = mysql_num_rows( $result );
if ($num == 1){
$row = mysql_fetch_assoc($result);
echo json_encode($row);
}else{
echo('Invalid');
}
?>
Can anyone advise me on how best to integrate jQuery in order to allow the document browser window to write the response...
If you use jQuery, you can easily use jQuery.getJSON()[DOCS] as follows:
$.getJSON('mypage.php', function(data) {
//Do somewith with JSON data
});
For normal Javascript, use
var xmlhttp;
if(window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else//IE5, IE6
xmlhttp = ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.Status == 200)
{
var response = JSON.parse(xmlhttp.responseText);
//Do something with JSON Data
}
};

error in json function saving data into database

I have tried a lot but I have not been able to find out what is wrong with this function to save two values into database. It has been working fine for another function to save one value. It behaves very strange here. Sometimes send 'parent' value & sometimes stop sending it but never send msg value. Here is function. It works fine for one input i.e. parent but problems start with the addition of 2nd input.
<script>
function ADDLISITEM(form)
{
var parent = form.txtInput.value;
var msg = form.msgInput.value;
form.txtInput.value = "";
form.msgInput.value = "";
var url = "send_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
}
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
//alert('POST');
} else {
alert(request.status); // fails here
}
}
}
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" +
encodeURIComponent(msg).replace(/%20/g, '+'));
}
</script>
This is send.php
$username = "babar";
$password = "k4541616";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
//die(var_export($_POST,TRUE));
$parent = $_POST['parent'];
$msg = $_POST['msg'];
$name = 'Akhtar Nutt';
//$parent2 = json_decode($parent);
$msg_ID = '2q7b2sfwwe';
//$msg2 = json_decode($msg);
$query = "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES
('','$name','$msg','$msg_ID','$parent')";
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error())
;}
?>
Alter
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
to:
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
You're missing the argument separator & in your query string...
You also might want to refrain from using values in $_REQUEST as they aren't reliable. If your script expects data from a POST then retrieve these values from $_POST.

Categories