How to figure out where this database insertion and retrieval is breaking? - php

Problem solved...variable undefined. I will add full answer when stackoverflow allows me to answer own question
update, firebug is telling me that the variable barrister is undefined in plugin.php but I do define that variable (or at least I try to)
this is the line where it's supposedly undefined: if(barrister.attr("value"))
this is the line where I try to define it: var barrister = $('input:radio[name=barrister]:checked').val();
I'm using a form with a radio button to submit data. The file plugin.php is supposed to get the data using javascript/ajax and then send it to results.php so that it can be inserted into the database. Information's also retrieved from the database and is supposed to be inserted into the html. I can't figure out where it's breaking down, but I do know the database connection itself works. Any idea how I might find out the broken link? When I test it and check the database, there's no data in it.
The form
<form method="post" id="form">
<table>
<tr>
<td><label>Barrister's Exam</label></td>
<td><input type="radio" id="barrister" name="barrister" value="1" /> Pass</td>
<td><input type="radio" id="barrister" name="barrister" value="0" /> Fail</td>
</tr>
<tr>
<td>Submit</td>
<td><input id="send" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
Getting the form data with plugin.php
function my_function() { ?>
<script type="text/javascript">
$(document).ready(function(){
//global vars
var barrister = $('input:radio[name=barrister]:checked').val();
var loading = $("#loading");
var messageList = $(".content > ul");
//functions
function updateShoutbox(){
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=update",
complete: function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000);
}
});
}
//check if all fields are filled
function checkForm(){
if(barrister.attr("value"))
return true;
else
return false;
}
//Load for the first time the shoutbox data
updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){
var barrister = barrister.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to results.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
});
</script>
<?php
}
add_action('wp_head', 'my_function');
putting the data into "results" table of the database "year" with results.php I know the database connection works
<?php
define("HOST", "host");
define("USER", "user");
define("PASSWORD", "password");
define("DB", "year");
/************************
FUNCTIONS
/************************/
function connect($db, $user, $password){
$link = #mysql_connect($db, $user, $password);
if (!$link)
die("Could not connect: ".mysql_error());
else{
$db = mysql_select_db(DB);
if(!$db)
die("Could not select database: ".mysql_error());
else return $link;
}
}
function getContent($link, $num){
$res = #mysql_query("SELECT barrister FROM results ORDER BY date DESC LIMIT ".$num, $link);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
function insertMessage($barrister){
$query = sprintf("INSERT INTO results(barrister) VALUES('%s');", mysql_real_escape_string(strip_tags($barrister))
));
$res = #mysql_query($query);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
/******************************
MANAGE REQUESTS
/******************************/
if(!$_POST['action']){
//We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php
header ("Location: index.html");
}
else{
$link = connect(HOST, USER, PASSWORD);
switch($_POST['action']){
case "update":
$res = getContent($link, 100);
while($row = mysql_fetch_array($res)){
$result .= "<li><strong>".$row['user']."</strong><img src=\"http://eslangel.com/wp-content/plugins/myplugin/CSS/images/bullet.gif\" alt=\"-\" />".$row['message']." </li>";
}
echo $result;
break;
case "insert":
echo insertMessage($_POST['barrister']);
break;
}
mysql_close($link);
}
?>
The html where the data is returned to when retrieved from the database
<div id="container">
<ul class="menu">
<li></li>
</ul>
<span class="clear"></span>
<div class="content">
<div id="loading"><img src="http:///></div>
<ul>
<ul>
</div>
</div>

The first error I notice is that all of your radio buttons have the same ID. An ID attribute should be unique on the page. Besides this, the best tool for debugging javascript is the console.
Javascript Debugging for beginners
EDIT
Here's an example of an ajax form submit using your markup http://jsfiddle.net/UADu5/
$(function(){
// Submit form via ajax
$('#check').click(function(){
var barrister = null
$.each($("input[name='barrister']:checked"), function(){
if($(this).val() == 1)
barrister = $(this).attr('value');
});
if(barrister){
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php",
data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
} else {
alert('Please fill all fields!')
}
})
})
<form method="post" id="form">
<fieldset>
<legend>Grade Exams</legend>
<ul>
<li>
<p>Barrister's Exam</p>
<label>
<input type="radio" name="barrister" value="1" /> Pass
</label>
<label>
<input type="radio" name="barrister" value="0" /> Fail
</label>
</li>
<li class="submit">
<input type="button" id="check" value="Test">
</li>
</ul>
</fieldset>
</form>

I strongly recommend using Firebug, as it will show you all the requests being made and all the request/response header info so you can see if and where the AJAX is going wrong. It's also great for debugging HTML/CSS stuff!
Firebug practically changed my life when it comes to JavaScript and CSS.

I think you have error in insert statement:
//remove extra bracket and semicolon
sprintf("INSERT INTO results(barrister) VALUES('%s')", mysql_real_escape_string(strip_tags($barrister))
);
Hope it helps

Change
var barrister = $('input:radio[name=barrister]:checked').val();
to
barrister = $('input:radio[name=barrister]:checked');
should help.

Related

Update database table without HTML form tag and get a specific value from MySQL table and display

I currently have a database table with 2 columns: Photo No. & Vote Count.
I would like to increase the vote count number in the database when the respective photo is pressed on the html page. Also, I did not want to go to another page as there's a overlay content when the photo is pressed. (thus there's no action in the form tags.
HTML
<form action="" method="post">
<input id="box1" type="submit">
<input id="result1" name="result1" type="text" value="0"/>
</form>
PHP
<?php
$link = mysqli_connect("localhost", "root", "", "votingcount");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "UPDATE vote_result SET vote_count = vote_count + 1 WHERE photo_no=1";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
to run php
$(function() {
$('form').bind('submit', function(){
$.ajax({
type: 'post',
url: "insert.php",
data: $("form").serialize(),
success: function() {
}
});
return false;
});
});
What I've done was to only allow the first photo vount count to be updated in the database. But I have 7 other photos which I would also like to update the respective vote count when the respective photos are clicked.
Does this could fit your needs ?
var votes = [0, 0, 0];
$(document).ready(function() {
$('.photoButton').click(function() {
// Here, make you ajax call using photo_id
++votes[$(this).parent().attr('photo_id')];
$(this).prev().text(votes[$(this).parent().attr('photo_id')]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="#photo-gallery">
<div class="photo" photo_id="0">
<img src="http://lmsotfy.com/so.png" style="width:100px" />
<span class="vote">0</span> <span class="photoButton">+</span>
</div>
<div class="photo" photo_id="1">
<img src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px" />
<span class="vote">0</span> <span class="photoButton">+</span>
</div>
<div class="photo" photo_id="2">
<img src="https://www.stackoverflowbusiness.com/hubfs/logo-so-color.png?t=1484933198957" style="width:100px" />
<span class="vote">0</span> <span class="photoButton">+</span>
</div>
</div>
Using ajax (this is the idea, it's not properly tested) :
$(function() {
$('.photoButton').click(function(){
$.ajax({
type: 'post',
url: "insert.php",
data: {
'photo_id' : $(this).parent().attr('photo_id')
},
success: function(data) {
$(this).prev().text(data['vote']);
}
});
return false;
});
});
And PHP :
try {
$sql->prepare("UPDATE vote_result SET vote_count = vote_count + 1 WHERE photo_no=:photo_id")
->bind('photo_id', $_GET['photo_id'])
->execute();
echo json_encode(array('vote' => $sql->query('SELECT vote_count FROM vote_result WHERE photo_no=:photo_id')->bind('photo_id', $_GET['photo_id'])->fetch()->vote_count));
} catch(SqlException $e){
// Deal with SQL errors or wrong IDs or ...
// depending on how your sql wrapper works
}
As I say, this is minimalist and just the idea of making this to work properly.
EDIT : You shouldn't use mysqli_* functions directely, prefer the use of PDO or any other SQL wrapper and use prepare and/or binding queries to prevent your code form SQL injection
at the time of image click we need to do update using ajax
data-id needs to unique for each image
the id of hidden field and the image data-id needs to be same
<div>
<img src="path/to/image" data-id="vote1" class="vote"/>
<input type="hidden" id="vote1" value="0">
</div>
<div>
<img src="path/to/image" data-id="vote2" class="vote"/>
<input type="hidden" id="vote2" value="1">
</div>
and in juery
$(documnet).on('click', '.vote', function(){
var imageId = $(this).attr("data-id");
var voteCnt = $("#"+imageId).val()+1;
$.post("process.php", { Photo:imageId, vote:voteCnt }
function(data){
//please use success or failure function
$("#"+imageId).val(voteCnt);
alert(data);
});
});

JQuery/AJAX script not sending data to php file?

I am making a question/status posting system using JQuery and Ajax however an error is being displayed "Notice: Undefined index: status in C:\xampp\htdocs\deadline\data.php on line 5" which is my line of code "$var = $_POST['status']; "
My system works as you have to log in to post a question(using sessions) BUT the issue is with my JQuery/AJAX script as the data that I have on homepage.php is not being sent to data.php (from my understanding which is why my index 'status' is undefined).
MY CODE
<?php
include("connection.php");
session_start();
if(isset($_SESSION['user_id']) && $_SESSION['user_id'] != "") {
}
else {
header("location:login.php");
}
$sid = $_SESSION['user_id'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM `users` WHERE id='{$sid}'";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
$fname = $result['fname'];
$lname = $result['lname'];
$time = time();
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = 'status='+status;
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
</head>
<body>
<div id="global">
<form action="" onsubmit="return false">
<textarea id="status"></textarea>
<button id="postbutton">POST</button>
LOGOUT
</form>
<br/>
<br/>
<div id="allstatus">
<!-- SKELETON -->
<div id="status">
<div id="statuspic">
</div>
<div id="statusinfo">
<div id="statusname">JOnathan</div>
<div id="statustext"> this is the question</div>
<div id="statusoption"><button id="likestatus">LIKE</button></div>
<div id="statusoption"><button id="commentstatus">COMMENT</button></div>
<div id="statusoption"><button id="sharestatus">SHARE</button></div>
<div id="statusoption"><button id="statustime">TIME</button></div>
</div>
</div>
<!-- SKELETON -->
</div>
</div>
</body>
</html>
<?php
$var = $_POST['status'];
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'forum';
//connecting
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
} else {
echo " success";
}
$sql = "INSERT INTO `question`(id, question) VALUES ('', '{$var}')";
$result = $conn->query($sql);
if($result) {
echo "inserted successfuly";
}
else {
echo "failed: " . $conn->error;
}
echo " the text: " .$var. " has been added to database.";
?>
HOW IT SHOULD WORK
I want to use JQuery/AJAX on my homepage.php to send data to data.php and that data gets returned back to homepage.php. On success to be displayed in my div #statustext.
Meaning when i write a question in textarea input field the data gets stored in database and retrieved and displayed in my div on the browser.
Please help me thanks..
you should change your script like below. Ajax sends data to url in a serialize manner either you have to use form serialize which will send all the fileds info to your php url other wise if you have to send only one field value then you can do this change
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = {'status='+status};
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
First of all use .val() not .value() when you getting value of your message. Second mistake - is using two id = "sattus". Id of elements must be unique or use class = "" for ident your class of elements.
Don't give same id to more then 1 html element !
In your code :
<textarea id="status"></textarea>
and
<div id="status">
both contains same id ! Please correct it first.Also In your code as Spencer mentioned in his answer that add name attribute with value "status". No doubt as you are using jQuery selector it should pick up correct one,though you can just alert it before sending the request using AJAX.
also set data variable as var data = {status : status};
POST uses name and not id so change this:
<textarea id="status"></textarea>
To this:
<textarea name="status"></textarea>
For the data make sure it's the data for your form, and add method="post" to it so it can send POST data. For example if you gave your form an id of yourForm:
HTML
<form action="" method="post" id="yourForm" onsubmit="return false">
JS
$.ajax({
...
data: $("#yourForm").serialize(),
...
});

Textarea breaking MySQL UPDATE query

is there a common problem that would cause my textarea to break the update query if it has more text than a single sentence in it?
The update query runs fine when I only input a single sentence, but anything more than a sentence breaks the query.
Here is the form code:
<form id="cp_files_admin_form" method="post" enctype="multipart/form-data">
<label>File Manager Login Text</label>
<input id="login_text" type="text" name="login_text" value="File Manager Login">
<hr>
<label>File Manager Login Logo</label>
<input id="login_logo" type="file" name="login_logo">
<hr>
<label>Main Left Logo</label>
<input id="main_left_logo" type="file" name="main_left_logo">
<hr>
<img class="form-img" src="" alt="">
<label>Main Center Logo</label>
<input id="main_center_logo" type="file" name="main_center_logo">
<hr>
<label>File Manager Instructions Text</label>
<textarea id="instructions_text" name="instructions_text" style="width:630px;height:150px;"></textarea>
<input id="submit" type="submit" value="Submit">
</form>
Here is the jQuery code:
$(document).ready(function() {
// Update CMS
$(document).on('click', '#submit', function() { // catch the form's submit event
// Send data to server through the ajax call
// action is functionality we want to call and outputJSON is our data
// fetch the data for the form
var data = $('#cp_files_admin_form').serialize();
console.log('Form Data Before Sent: '+data);
$.ajax({
url: 'update.php',
data: data,
type: 'GET',
async: 'true',
dataType: 'json',
success: function (result) {
if(result.status) {
alert('CMS Update Successful!');
getCMS();
} else {
alert('CMS Update unsuccessful!');
}
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
return false; // cancel original event to prevent form submitting
});
});
Here is the update.php code:
<?php
header("Access-Control-Allow-Origin: *");
require_once("debug/chromephp.php");
$formData = $_GET;
ChromePhp::log('$_GET Data: '.$formData['instructions_text']);
require_once("config.php");
$login_text = $formData['login_text'];
//$login_logo = $formData['login_logo'];
//$main_left_logo = $formData['main_left_logo'];
//$main_center_logo = $formData['main_center_logo'];
$instructions_text = $formData['instructions_text'];
$sql="UPDATE cp_cms SET login_text='$login_text', instructions_text='$instructions_text' WHERE id = 1";
$result = mysql_query($sql);
if($result) {
// Success
$output = array('status' => true, 'massage' => 'Success!');
echo json_encode($output);
} else {
// Failed
$output = array('status' => false, 'massage' => 'Failed!');
echo json_encode($output);
}
?>
Screenshot of table structure:
Any help is much appreciated.
try this, it prevents entries in the form from breaking your sql queries. Which is also called SQL-Injection Attack ...
$sql="UPDATE cp_cms SET login_text='".
mysql_real_escape_string($login_text)."', instructions_text='".
mysql_real_escape_string($instructions_text)."' WHERE id = 1";
but please have a look at PDO it is so much safer and easier ...
Edit: I dug some PDO example up:
http://www.phpeveryday.com/articles/PDO-Prepared-Statement-P552.html

updating combo values

I have a combo that simply displays some mysql databases. I also have a form that creates a database. I would like to dynamicly refresh the combo (if possible) to also display the new database created by the form. here is a snippet of the code:
<div id="tools">
<P>Add a Set list:<br>
<LABEL for="labelName">Set List Name: </LABEL>
<INPUT type="text" name="slName" id="slName"><button id="createSL" value="Create Setlist">Create Set</button>
</P><br>
<P>Delete a Set list:<br>
<? include("remSLcombo.php"); ?> <button href="#" type="button" id="delSl">Delete Setlist</button>
</P>
<p>Check how to reload combos</p>
</div><BR>
<? include("combo.php"); ?>
The Jquery function that is called to create the database:
$('#createSL').click(function(){
var sendIt = $("#slName").val();
$.ajax({
type: "POST",
url: "createSL.php",
data: {slName : sendIt},
error: function(e){
alert("The PHP Call failed! hmmm");
alert(e.status);
},
success: function(response){
alert(response);
}
});
$("#selcombo").load("combo.php");
$("#tools").hide().html(data).fadeIn('fast');
});
Combo.php:
<?php
echo '<select id="tunelist" name="tunelist" >';
$link = mysql_connect('localhost', 'setlist', 'music');
$query = mysql_query("SHOW DATABASES");
echo '<option>Select a Show</option>';
while ($row = mysql_fetch_assoc($query)) {
if ($row['Database'] == "information_schema"){}
elseif ($row['Database'] == "performance_schema"){}
elseif ($row['Database'] == "mysql"){}
else{
echo '<option value="'.$row['Database'].'">'.$row['Database'].'</option>';
}
}
echo '</Select>';
?>
How do I go about refreshing the values in the combo (made by combo.php) after a database is added using the form above?
Any help as always is greatly appreciated!
Loren
Try moving
$("#selcombo").load("combo.php");
to inside of your success function:
success: function(response){
alert(response);
if (response == true) // or something like this to ensure the success of the operation
$("#selcombo").load("combo.php");
}
What you have to do is to give back in createSL.php the code of the new combobox and loaded there.
This is your code
success: function(response){
alert(response);
}
Write something like:
success: function(response){
$('#tunelist').html(response);
}
Where the response is similar to Combo.php

Post result from a query via php in same page with Ajax

I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.

Categories