Textarea breaking MySQL UPDATE query - php

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

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);
});
});

Add the last added database record right after form submission

I have a registration form and I want to display all of the registrants. I want to output whatever records are in the database and then once the form is submitted to register another display that record as well.
I can successfully register the records and display them using ajax however It does not load the last registered record until you reload/comeback to the page. I want the last record to just join its brethren right after the form submits. I appreciate anything you can suggest.
home.php
<form id="register-student" method="post" action="process_student_registration.php" class="basic-form not-toggled">
<h2>Enter Student Info to Register</h2>
<fieldset id="student-name-group" class="form-group">
<div class="split">
<fieldset id="student-firstname-group">
<label for="student-first-name">First Name:</label>
<input id="student-first-name" type="text" name="student_first_name">
</fieldset>
</div>
<div class="split">
<fieldset id="student-lastname-group">
<label for="student-last-name">Last Name:</label>
<input id="student-last-name" type="text" name="student_last_name">
</fieldset>
</div>
</fieldset>
<fieldset class="submit-button">
<div id="loading" class="hidethis"><img id="loading-image" src="../../images/ajax-loader.gif" alt="Loading..." /></div>
<button id="register-student-button" type="submit" class="btn btn-success" name="register-student-button">Register Student</button>
</fieldset>
</form>
<script>
$(document).ready(function() {
var students = $.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "fetch_students.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#registered-students").html(response);
//alert(response);
}
});
});
</script>
<div id="registered-students"></div><!--End # registered-students-->
fetch_students.php
<?php
//Fetch the Students
//First lets make sure the user is allowed
require_once('../auth/agency_session.php');
//App Functions
require_once('../../includes/functions/app_functions.php');
//Agents Home Page
require_once('../../db_config.php');
$db_connect = connectDB($mysqli);
$agency_id = $_SESSION['ID'];
//Here we display all the students the agent has registered
//First check the connection
if(!mysqli_connect_errno()){
if($stmt = $db_connect->prepare("SELECT student_id, student_first_name, student_last_name, student_email FROM students WHERE agency_id = ?")){
//Bind Parameters
$stmt->bind_param('i', $agency_id);
//Execute
$stmt->execute();
//Store Results
$stmt->store_result();
//Get the rows
$num_rows = $stmt->num_rows;
//Bind the results
$stmt->bind_result($student_id, $student_first_name, $student_last_name, $student_email);
if($stmt->num_rows < 1){
echo'<h3>No Students Registered</h3>';
}
else{
//Fetch the values
echo'<h3>Registered Students</h3>';
echo'<ul class="grid">';
while($stmt->fetch()){
echo '<li id="'.$student_id.'" class="col">'.$student_first_name.' '.$student_last_name.'<span>'.$student_email.'</span></li>';
}//End While
echo'</ul>';
}//End else
}//End if no prepare statment happens
}//End if No connection
?>
process_student_registration.php
jQuery(document).ready(function($){
// Get the form and place it into a variable
var form = $('#register-student');
//Creating an Event Listener for the submit buttom on the contact form
$(form).submit(function(event){
$('.form-group').removeClass('.has-error');//Remove the error class on the things that have the error class
$('.error-message').remove();//Remove the error messages completeley
//Serialize the Form Data (Converts the data the user has entered into a key/value string that can be sent with an AJAX request)
var formData = $(form).serialize();
//Submit the form using AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType :'json',
encode:true
//.done refers to a successful completion of the form
})
.done(function(data){
//Log the data into the console so that we can be sure what is happening
console.log(data);
//If we do have errors create the
if(!data.successmessage){
if(data.errors){
$('.error').remove();
$('.error-message').remove();
$('#register-student').addClass('form-has-error'); // add the form-has-error-class
$('#register-student-button').after('<p class="error">Please check the errors above.</p>');
$(form).removeClass('success');
$('.submit-success').remove();
if(data.errors.student_first_name){
$('#student-firstname-group').addClass('has-error'); // add the error class to show red input
$('#student-firstname-group').append('<div class="error-message"><p>' + data.errors.student_first_name + '</p></div>'); // add the actual error message under our input
}
if(data.errors.student_last_name){
$('#student-lastname-group').addClass('has-error'); // add the error class to show red input
$('#student-lastname-group').append('<div class="error-message"><p>' + data.errors.student_last_name + '</p></div>'); // add the actual error message under our input
}
}
} else if(data.successmessage){
//Remove the errors stuff
$('.error').remove();
$('.error-message').remove();
$('#register-student').removeClass('form-has-error'); // add the form-has-error-class
$('#blocking').removeClass('hidethis').addClass('showthis');
$('#loading').removeClass('hidethis').addClass('showthis');
$('.submit-success').remove();
//Add the success stuff
$(form).addClass('success');
setTimeout(function(){
$('#blocking').removeClass('showthis').addClass('hidethis');
$('#loading').removeClass('showthis').addClass('hidethis');
$('#register-student').append('<div class="submit-success"><p>' + data.successmessage + '</p></div>');
$(form).find('input, :text').val('');
//Run the Get operation on the database to add newly added records to the list
}, 5000);
//Clear the form upon successful completion
}
//.fail referes to an unsuccessful completion of the form
})
.fail(function(data){
//If there is a failed submission lets log the errors
console.log(data);
});
//Stop the broweser from submitting the form
event.preventDefault();
});
});
I had a similar issue... you are processing from two different php file:
process_student_registration.php and fetch_students.php
I believe your problem might be solved if you do all the processing from one file:
You are only passing two pieces of data. Rather than collecting the data from a form you can collect the data through inputs and go straight to the jQuery.
Your Collection HTML would look like this: NOTICE the dashes replaced with underscores.
<h2>Enter Student Info to Register</h2>
<input type="hidden" id="processStudent" value="process_student_registration.php">
<fieldset id="student-name-group" class="form-group">
<div class="split">
<fieldset id="student_firstname_group">
<label for="student_first_name">First Name:</label>
<input id="student_first_name" type="text" name="student_first_name">
</fieldset>
</div>
<div class="split">
<fieldset id="student_lastname_group">
<label for="student_last_name">Last Name:</label>
<input id="student_last_name" type="text" name="student_last_name">
</fieldset>
</div>
</fieldset>
<fieldset class="submit_button">
<div id="loading" class="hidethis"><img id="loading_image" src="../../images/ajax_loader.gif" alt="Loading..." /></div>
<button id="register_student_button" type="submit" class="btn btn_success" name="register_student_button">Register Student</button>
</fieldset>
<div id="registered-students"></div>
Your jQuery...
<script>
$(document).ready(function() {
$( "#register-student-button" ).click(function(){
var url = $('#processStudent').val();
var student_first_name = $('#student_first_name').val();
var student_last_name = $('#student_last_name').val();
var postit = $.post( url, {student_first_name:student_first_name,student_last_name:student_last_name});
postit.done(function( data ) {
alert('Student has been processed');
$('#registered-students').html(data);
});
});
});
Your PHP...
<?php
$student_first_name = $_POST['student_first_name'];
$student_last_name = $_POST['student_last_name'];
// PROCESS REGISTRATION HERE AS YOU ARE
// FETCH STUDENTS HERE AS YOU ARE
?>
I have figured out a solution. Basically I run the script to display records fomr the database on once on page load. Then I took basically the same script again and run it once more upon successful completion of the form. This way we only scan the database for new records as we need to. Not sre if it the most elegant or efficient way but she work like a charm.
So in my process_student_registration.php I added this to the success message.
//Run the Get operation on the database to add newly added records to the list
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "fetch_students.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#registered-students").html(response);
//alert(response);
}

Preventing form from refreshing page Javascript

im quite bad at javascript, and i am trying to make a AJAX call, but i get my value from a form feild, and it just refreshes the page, cant even observe if the AJAX call is succesfull.
Here is my HTML:
<form class="form-horizontal" id="subscribe-form" name="subscribe-form" onSubmit="return subscribe();">
<fieldset>
<p>
Subscribe
</p>
<div class="input-prepend input-append">
<input name="subscribwEmail" class="span2" id="InputEmail" type="email" placeholder="Email">
<input type="submit" class="btn btn-inverse" />
</div>
</fieldset>
</form>
JS:
function subscribe() {
var emailForm = $('#subscribwEmail').val();
$('#subscribe-form').hide(); // hide email form
$('#subscribeDiv').prepend('<img id="process" src="http://www.mydomain.com/assets/img/process.gif" />')
$.ajax({
type: "POST",
url: "../../actions/ajax-subscribe.php",
data: {
email: emailForm
},
dataType: "json",
success: function (data) {
if (data[0] == 1) { // test if response was 1 or 2
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>Thank you for subscribing!</p>');
} else {
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>There was an error subscribing the email.</p>');
}
}
})
};
ajax-subscribe.php
<?php
include ('phpfunctions.php');
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('ERROR WITH SQL CONNECTION CONTACT ADMIN');
$email = cleanString($con, $email);
$query = "INSERT INTO `subscribers` (`email`, `ip`) VALUES ('$email', '$ip');";
if ($result = mysqli_query($con, $query)) {
echo json_encode(1); // all ok inserted
} else {
echo json_encode(0); // failed
}
?>
You do not cancel the click event so the form submits.
Add return false; to the end of your subscribe method.
You have to return false from your subscribe method
Also you can validate the email, if it is invalid, you can stop sending subscribe by return false
You can also disable your submit button. (formObj comes with subscribe parameter)
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
But you have to enable it if something goes wrong.

ajax update to database

I am trying to add data to a database and for some reason it does not always work. I'd say 80% of the time it will work and I'll see the result in the database but sometimes its like the script won't run.
here is the ajax :
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('.error').hide();
$("#success").hide();
$(".button").click(function () {
$('.error').hide();
var name = $("input#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: $("input#name"),
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
});
});
});
});
</script>
here is the html:
<div id = "contact_form">
<form name ="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="send" />
</fieldset>
<span id="success"> the name has been updated successfully!</span>
</form>
</div>
<div id ="upd"></div>
and here is the proccess.php file:
<?php
$va = $_POST["name"];
$dbconnection = mysql_connect('adatabase','someuser','somepw');
if(!mysql_select_db('some_database', $dbconnection)) {
echo mysql_error();
}
else
{
echo 'connection success';
}
$sql = "INSERT INTO some_db(text) VALUES ('$va')";
$result = mysql_query($sql) or die('erreur sql!'.mysql_error());
if(!$result) {
echo "not working";
}
else {
echo "working";
}
?>
so how come it does not always insert into the database?
and is there a way to get the result from the php if(!$result) to show in the success part of the ajax?
You're actually passing a jQuery-Object to your PHP-File.
$.post("class/proccess.php", {
name: $("input#name").val() //Pass val() not the whole jQuery-Object!
}, function() {
/* success */
});
While you're debugging, make sure MySQL errors are enabled.
In your Javascript for the Ajax success handler, show an alert with the text returned from the call. That way if there's an error with MySQL you'll see it.
Another thing is, could the "text" field be set in the database as UNIQUE? Trying to insert a new record with a duplicate string would fail in that case.
And... the name of the field isn't really 'text' is it? I would recommend avoiding field names that are the same as the basic data types for MySQL. Just to avoid confusion if no other reason.
If it is not working sometimes, you need to check the returned string for errors. The right way to do this using AJAX is as follows.
You can include a parameter in your success callback which will fetch the page-result from the PHP.
Instead of
success: function () {
...
}
use
success: function (data) {
alert(data);
}
Change your ajax call to:
$.ajax({
type: 'POST',
url: "class/proccess.php",
data: {name : $("input#name").val()},
cache: false,
success: function () {
$("#success").fadeIn(200).show();
}
So that $_POST['name'] is set to the value of your input box.
Also, as suggested, you should change your mysql functions to mysqli functions to help protect against sql injections.

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

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.

Categories