I need assistance in figure out the method to provide a button to reset these checkboxes.
UPDATEL: I have more information to share:
The answers provided will only work with checkboxes that are selected with that instance and not checkboxes that are enabled onLoad. This is a perferences page were people can choose genre's they like and save them.
<div class="grid_13">
<form method="post" id="updatePreferedGenres" action="/account/update/preferences/genres">
<h2 class="alt blue no-margin-top margin-bottom">Check off genres you like:</h2>
<?php
$this->load->library('GenreLib');
$genreArray = $this->genrelib->getGenreList();
foreach ($genreArray as $parentID => $genreSegment){
$isChecked = "";
if (isset($customerPrefs['genres']) && is_array($customerPrefs['genres']) && sizeof($customerPrefs['genres']) > 0 && in_array($parentID, array_keys($customerPrefs['genres']))) {
$isChecked = "CHECKED";
}
echo '<p class="grid_3 no-margins-left no-margins-right"><input type="checkbox" class="margin-right" name="' . $genreSegment['parentGenreName'] . '" value="' . $parentID . '"' . $isChecked . '/>' . $genreSegment['parentGenreName'] . '</p>';
}
?>
<div class="clear"></div>
<input type="button" class="button right" value="Save" />
<div class="clear"></div>
</form>
// Rig the preferences form
$("#updateDHOverride").submit(function(event) {
event.preventDefault();
if ( $(this).find("#downloadHubOverride").is(':checked')){
document.cookie = 'downloadHubOverride=TRUE; expires=Thursday, 25-Jul-2030 23:59:59 GMT; path=/';
}
else {
document.cookie = 'downloadHubOverride=FALSE; expires=Thursday, 25-Jul-2030 23:59:59 GMT; path=/';
}
});
// Rig the submit for genre preferences form
$("#updatePreferedGenres").each(function() {
var linkedForm = $(this);
$(this).find("#prefSave").click( function(event) {
event.preventDefault();
var getGenreIds = "";
linkedForm.find("input[type=checkbox]").each( function() {
if ( $(this).is(":checked") ) {
if ( getGenreIds.length > 0) {
getGenreIds += ',' + $(this).attr('value');
}
else {
getGenreIds += $(this).attr('value');
}
}
});
$.post(
linkedForm.attr('action'),
{ genreIds : getGenreIds },
function (status) {
status = $.parseJSON(status);
if ( status.status == "success" ) {
$.prompt('<h4>Preferences updated successfully!</h4>', {
top: '34%',
zIndex: '10000'
});
if ( linkedForm.hasClass('goHome') ) window.location = "/";
}
else {
$.prompt('<h4>' + status.message + '</h4>', {
top: '34%',
zIndex: '10000'
});
}
}
);
});
});
// REMOVE checkboxes Script - need to place into onClick Function
// $('input:checkbox').removeAttr('checked');
$('#activateAccount').submit( function(event) {
event.preventDefault();
// update form update action
$.post(
$(this).attr('action'),
$(this).serialize(),
function (status) {
//console.log(status);
status = $.parseJSON(status);
if ( status.status == "success" ) {
$.prompt('<h4>Account updated successfully!</h4>', {
top: '34%',
zIndex: '10000',
buttons: { OK:true },
submit: function(v,m,f){
location.reload(true);
}
});
}
else {
if ( status.data != "" ) {
//if there are form validation errors
displayValidation(status.data);
}
else {
//generic error message
$.prompt('<h4>' + status.message + '</h4>', {
top: '34%',
zIndex: '10000'
});
}
}
}
);
});
I have a basic Idea of what needs to happen, I'm just not sure on the syntax.
since you seem to only have checkboxes :
<input type='reset' value='resetButton'>
No need for PHP, nor Javascript:
<input type="reset" value="Reset checkboxes" />
Related
I'm trying to create a form that has a drag and drop image with it. I did a tutorial for the drag and drop and now I'm trying to
put it together with a form.
The problem I'm having is that I'm not able to get the filename, so that I can insert it into the database.
I've tried doing this
if(isset($_POST['add_product']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
but I get a blank array
Array ( [0] => ) 1
and when I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
echo print_r($filename);
die();
}
I get the name of my image, but if I do this
if(isset($_FILES['files']))
{
$filename = $_FILES['files']['name'];
}
if(isset($_POST['add_product']))
{
echo print_r($filename);
die();
}
I get a blank array as well
Array ( [0] => ) 1
Here I was hoping that I could grab the $filename and pass it on to the if(isset($_POST['add_product]))
Here is my form
<form action="" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="content">content</label>
<textarea name="content" id="content" class="form-control" cols="30" rows="10"></textarea>
</div>
<input type="file" name="files[]" id="standard-upload-files" multiple>
<input type="submit" value="Upload files" id="standard-upload">
<div class="wrapper">
<div class="upload-console">
<h2 class="upload-console-header">
Upload
</h2>
<div class="upload-console-body">
<div class="upload-console-drop" id="drop-zone">
just drag and drop files here
</div>
<div class="bar">
<div class="bar-fill" id="bar-fill">
<div class="bar-fill-text" id="bar-fill-text"></div>
</div>
</div>
<div class="hidden" id="uploads-finished">
<h3>Process files</h3>
<div class="upload-console-upload">
filename.jpg
<span>Success</span>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-dark btn-lg btn-block" name="add_product">Save</button>
</div>
</form>
Here is the js files that I got from the tutorial that I did.
main.js
(function(){
"use strict";
var dropZone = document.getElementById('drop-zone');
var barFill = document.getElementById('bar-fill');
var barFillText = document.getElementById('bar-fill-text');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files){
// console.log(files);
app.uploader({
files: files,
progressBar: barFill,
progressText: barFillText,
processor: 'index.php',
finished: function(data){
// console.log(data);
var x;
var uploadedElement;
var uploadedAnchor;
var uploadedStatus;
var currFile;
for(x = 0; x < data.length; x = x + 1)
{
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'upload-console-upload';
uploadedAnchor = document.createElement('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded)
{
uploadedAnchor.href = 'uploads/'+currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function(){
console.log('there was an error');
}
});
};
//drop functionality
dropZone.ondrop = function(e){
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function(){
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function(){
this.className = 'upload-console-drop';
return false;
};
}());
upload.js
var app = app || {};
(function(o){
"use strict";
//private methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState === 4)
{
if(this.status === 200)
{
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function')
{
o.options.finished(uploaded);
}
}else{
if(typeof o.options.error === 'function')
{
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(e){
var percent;
if(e.lengthComputable === true)
{
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1)
{
data.append('files[]', source[i]);
}
return data;
};
setProgress = function(value){
if(o.options.progressBar !== undefined)
{
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined)
{
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options){
o.options = options;
if(options.files !== undefined)
{
ajax(getFormData(o.options.files));
// getFormData(o.options.files);
}
}
}(app));
I have a problem with receiving data from AJAX using the POST method.
At first, everything worked properly, but then something happened and now I can't find the bug.
If I check my AJAX everything dispatched properly, but PHP does not receive the data. As a result, it does not insert data into the database table.
My jQuery:
$('#button-send-review').click(function(e) {
e.preventDefault();
var th = $(this);
var name = $("#name_review").val();
var good = $("#good_review").val();
var bad = $("#bad_review").val();
var comment = $("#comment_review").val();
var iid = $("#button-send-review").attr("iid");
var add_review = $("#button-send-review").val();
if (name != "") {
var name_review = '1';
$("#name_review").css("borderColor", "#DBDBDB");
} else {
var name_review = '0';
$("#name_review").css("border", "2px solid #d20000");
}
if (good != "") {
var good_review = '1';
$("#good_review").css("borderColor", "#DBDBDB");
} else {
var good_review = '0';
$("#good_review").css("border", "2px solid #d20000");
}
if (bad != "") {
var bad_review = '1';
$("#bad_review").css("borderColor", "#DBDBDB");
} else {
var bad_review = '0';
$("#bad_review").css("border", "2px solid #d20000");
}
if (name_review == '1' && good_review == '1' && bad_review == '1') {
$.ajax({
type: "POST",
url: "./",
data: "goods_id=" + iid + "&name=" + name + "&good=" + good + "&bad=" + bad + "&comment=" + comment + "&add_review=" + add_review,
dataType: "html",
cache: false,
}).done(function() {
$(".success").addClass("visible");
setTimeout(function() {
// Done Functions
th.trigger("reset");
$(".success").removeClass("visible");
$.magnificPopup.close();
}, 3000);
});
}
});
My Controller:
<?php
if ($_POST['add_review']) {
add_review();
}
?>
My Model:
<?php
function add_review() {
global $link;
$goods_id = trim($_POST['goods_id']);
$name = trim($_POST['name']);
$good = trim($_POST['good']);
$bad = trim($_POST['bad']);
$comment = trim($_POST['comment']);
$goods_id = clear($goods_id);
$name = clear($name);
$good = clear($good);
$bad = clear($bad);
$comment = clear($comment);
$query = "INSERT INTO reviews(goods_id, name, good_reviews, bad_reviews, comment, date)
VALUES($goods_id, '$name', '$good', '$bad', '$comment', NOW())";
$res = mysqli_query($link, $query) or trigger_error($link->error . "[DB]");
return true;
}
?>
My HTML:
<div id="send-review" class="popup-form">
<div class="success">Thank you! <br>
Your review send for moderation.
</div>
<h4 id="title-review">The review would be posted soon.</h4>
<ul>
<li>
<label id="label-name"><span>Name *</span></label>
<input maxlength="15" type="text" id="name_review" placeholder="Enter your name..." style="border-color: rgb(219, 219, 219);" />
</li>
<li>
<label id="label-good"><span>Pros *</span></label>
<textarea id="good_review" placeholder="Enter pros..." style="border-color: rgb(219, 219, 219);"></textarea>
</li>
<li>
<label id="label-bad"><span>Cons *</span></label>
<textarea id="bad_review" placeholder="Enter cons..." style="border-color: rgb(219, 219, 219);"></textarea>
</li>
<li>
<label id="label-comment">Comment</label>
<textarea id="comment_review" placeholder="Your comment..."></textarea>
</li>
</ul>
<div class="button-wrap">
<button class="button" type="submit" id="button-send-review" name="add_review" value="Send" iid="92">Send</button>
</div>
<button title="Close (Esc)" type="button" class="mfp-close">×</button>
</div>
Your $.ajax() data isn't formatted correctly;
Should be like this example to receive the POST strings in your receiver page:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
});
And please use prepared SQL statements to secure against SQL Injections.
The posting format in the ajax method is incorrect;
change ajax code to :
<script>
$('#button-send-review').click(function (e) {
e.preventDefault();
var th = $(this);
var name = $("#name_review").val();
var good = $("#good_review").val();
var bad = $("#bad_review").val();
var comment = $("#comment_review").val();
var iid = $("#button-send-review").attr("iid");
var add_review = $("#button-send-review").val();
if (name != "")
{
var name_review = '1';
$("#name_review").css("borderColor", "#DBDBDB");
} else {
var name_review = '0';
$("#name_review").css("border", "2px solid #d20000");
}
if (good != "")
{
var good_review = '1';
$("#good_review").css("borderColor", "#DBDBDB");
} else {
var good_review = '0';
$("#good_review").css("border", "2px solid #d20000");
}
if (bad != "")
{
var bad_review = '1';
$("#bad_review").css("borderColor", "#DBDBDB");
} else {
var bad_review = '0';
$("#bad_review").css("border", "2px solid #d20000");
}
if (name_review == '1' && good_review == '1' && bad_review == '1')
{
$.ajax({
type: "POST",
url: "./",
data: {"goods_id":iid,"name":name,"good":good,"bad":bad, "comment":comment,"add_review":add_review},
dataType: "html",
cache: false,
}).done(function () {
$(".success").addClass("visible");
setTimeout(function () {
// Done Functions
th.trigger("reset");
$(".success").removeClass("visible");
$.magnificPopup.close();
}, 3000);
});
}
});
</script>
use PDO to stop SQl Injection
I have a code, in a file called service.php which does as follows:
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
// Code to add entry into database
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
And the file to send the data via POST method using AJAX is:
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
The action attribute of the form #addRunner is:
<form action="service.php" id="addRunner" name="addRunner" method="POST">
<!-- Form Elements -->
</form>
Note that the action attribute for the form element is simply service.php instead of service.php?action=addRunner. However, the form still works perfectly, and successfully adds new "runner" information into the database. How does this happen?
Shouldn't the condition ($_POST['action'] == 'addRunner') fail and prevent the code to enter data into the database from running?
For the sake of completeness, the entirity of my code is as below.
My HTML is:
<!DOCTYPE html>
<html>
<head>
<title>2011 Race Finishers</title>
<link href="styles/my_style.css" rel="stylesheet">
</head>
<body>
<header>
<h2>2011 Race Finishers!</h2>
</header>
<div id="main">
<ul class="idTabs">
<li>Male Finishers</li>
<li>Female Finishers</li>
<li>All Finishers</li>
<li>Add New Finishers</li>
</ul>
<div id="male">
<h4>Male Finishers</h4>
<ul id="finishers_m"></ul>
</div>
<div id="female">
<h4>Female Finishers</h4>
<ul id="finishers_f"></ul>
</div>
<div id="all">
<h4>All Finishers</h4>
<ul id="finishers_all"></ul>
</div>
<div id="new">
<h4>Add New Finishers</h4>
<form action="service.php" id="addRunner" name="addRunner" method="POST">
First Name: <input type="text" name="txtFirstName" id="txtFirstName"> <br>
Last Name: <input type="text" name="txtLastName" id="txtLastName"> <br>
Gender: <select name="ddlGender" id="ddlGender">
<option value="">--Please Select--</option>
<option value="m">Male</option>
<option value="f">Female</option>
</select> <br>
Finish Time:
<input type="text" id="txtMinutes" name="txtMinutes" size="10" maxlength="2">
<input type="text" id="txtSeconds" name="txtSeconds" size="10" maxlength="2">
<br><br>
<button id="btnSave" type="sumbit" name="btnSave">Add Runner</button>
<input type="hidden" id="action" name="action" value="addRunner">
</form>
</div>
</div>
<footer>
<h4>Congratulations to all our finishers!</h4>
<button id="btnStart">Start Page Updates</button>
<button id="btnStop">Stop Page Updates</button>
<br>
<span id="freq"></span><br><br>
Last Updated: <div id="updatedTime"></div>
</footer>
<script src="scripts/jquery-1.6.2.min.js"></script>
<script src="scripts/my_scripts.js"></script>
<script src="scripts/jquery.idTabs.min.js"></script>
</body>
</html>
My jQuery is:
$(document).ready(function(){
var FREQ = 10000 ;
var repeat = true;
function showFrequency(){
$("#freq").html( "Page refreshes every " + FREQ/1000 + " second(s).");
}
function startAJAXcalls(){
if(repeat){
setTimeout( function() {
getDBRacers();
startAJAXcalls();
},
FREQ
);
}
}
function getXMLRacers(){
$.ajax({
url: "finishers.xml",
cache: false,
dataType: "xml",
success: function(xml){
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$(xml).find("runner").each(function() {
var info = '<li>Name: ' + $(this).find("fname").text() + ' ' + $(this).find("lname").text() + '. Time: ' + $(this).find("time").text() + '</li>';
if( $(this).find("gender").text() == "m" ){
$('#finishers_m').append( info );
}else if ( $(this).find("gender").text() == "f" ){
$('#finishers_f').append( info );
}else{ }
$('#finishers_all').append( info );
});
getTimeAjax();
}
});
}
function getDBRacers()
{
$.getJSON("service.php?action=getRunners", function(json)
{
if(json.runners.length > 0)
{
$('#finishers_m').empty();
$('#finishers_f').empty();
$('#finishers_all').empty();
$.each(json.runners, function()
{
var info = '<li>Name: ' + this['fname'] + ' ' + this['lname'] + '. Time: ' + this['time'] + '</li>';
if(this['gender'] == 'm')
{
$('#finishers_m').append(info);
}
else if(this['gender'] == 'f')
{
$('#finishers_f').append(info);
}
else {}
$('#finishers_all').append(info);
});
}
});
getTimeAjax();
}
function getTimeAjax(){
var time = "";
$.ajax({
url: "time.php",
cache: false,
success: function(data){
$('#updatedTime').html(data);
}
});
}
$("#btnStop").click(function(){
repeat = false;
$("#freq").html( "Updates paused." );
});
$("#btnStart").click(function(){
repeat = true;
startAJAXcalls();
showFrequency();
});
showFrequency();
getDBRacers();
startAJAXcalls();
$("#btnSave").click(function()
{
var data = $("#addRunner :input").serialize();
$.post($("#addRunner").attr('action'), data, function(json)
{
if(json.status == 'fail')
alert(json.message);
if(json.status == 'success')
{
alert(json.message);
clearInputs();
}
},"json");
});
function clearInputs()
{
$("#addRunner:input").each(function(){
$(this).val('');
});
}
$("#addRunner").submit(function() {
return false;
});
});
And finally the contents of Service.php is:
<?php
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
{
$fname = htmlspecialchars($_POST['txtFirstName']);
$lname = htmlspecialchars($_POST['txtLastName']);
$gender = htmlspecialchars($_POST['ddlGender']);
$minutes = htmlspecialchars($_POST['txtMinutes']);
$seconds = htmlspecialchars($_POST['txtSeconds']);
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname))
{
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) )
{
fail('Please enter a first and last name.');
}
if( empty($gender) )
{
fail('Please select a gender.');
}
if( empty($minutes) || empty($seconds) ) {
fail('Please enter minutes and seconds.');
}
$time = $minutes.":".$seconds;
$query = "INSERT INTO runners SET first_name='$fname', last_name='$lname', gender='$gender', finish_time='$time'";
$result = db_connection($query);
if ($result)
{
$msg = "Runner: ".$fname." ".$lname." added successfully" ;
success($msg);
}
else
{
fail('Insert failed.');
}
exit;
}
else if($_GET['action'] == 'getRunners')
{
$query = "SELECT first_name, last_name, gender, finish_time FROM runners ORDER BY finish_time ASC";
$result = db_connection($query);
$runners = array();
while($row = mysqli_fetch_array($result))
{
array_push($runners, array('fname' => $row['first_name'], 'lname' => $row['last_name'], 'gender' => $row['gender'], 'time' => $row['finish_time']));
}
echo json_encode(array("runners" => $runners));
exit;
}
function db_connection($query)
{
$dbc = mysqli_connect('127.0.0.1','runner_db_user','runner_db_password','race_info')
or die('Error connecting to Database');
return mysqli_query($dbc,$query);
}
function fail($message)
{
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message)
{
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
It will work reason behind this is action is value of name attribute from hidden field. It is not the action of your form tag. If you want to make it fail for testing purpose you should change the value of hidden field to something else in your form and then check again.
This is your hidden field
<input type="hidden" id="action" name="action" value="addRunner">
You can do like this for testing only
<input type="hidden" id="action" name="action" value="addRunners">
It will not satisfy this if condition
if ((!empty($_POST)) && ($_POST['action'] == 'addRunner'))
i need to pass a get variable via jquery, one of the form fields is a multiple check box. so i want to be able to pass it so that from php i can use GET and collect it then use IMPLODE to get such a value but its not working
JQUERY CODE HERE
$(document).ready(function(){
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
$("#FilterForm :input").change(function() {
$(this).closest('form').data('changed', true);
var FilterByOrder = $("#FilterByOrder").val();
var location = $("#location").val();
var sortFilter = $("#sortFilter").val();
var Highlights = $("#Highlights").val();
if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
{
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
else
{
$.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, Highlights: Highlights}, function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
});
});
THE PHP VERSON
<?php
if(isset($_GET['FilterByOrder'])){
echo 'filter '. $FilterByOrder=$_GET['FilterByOrder'].'<br>';
echo 'location '.$location=$_GET['location'].'<br>';
echo 'sort '.$sortFilter=$_GET['sortFilter'].'<br>';
echo 'highlits '.$Highlights=$_GET['Highlights'].'<br>';
echo 'here is the one!';
}else
{
echo'lets run it';
}
?>
THE HTML FORM FIELD
<input type="checkbox" name="Highlights[]" value="<?php echo $DisplayedHighlightID; ?>" id="Highlights">
$(document).ready(function(){
var searchValue = $("#searchValue").val();
$.get('actionfilter.php', {searchValue: searchValue}function(data){
$('.disFilter').html(data).fadeIn("2000");
});
$("#FilterForm :input").change(function() {
$(this).closest('form').data('changed', true);
if($("#FilterByOrder").prop("checked") == true){
var FilterByOrder = 'on';
}
else
{
var FilterByOrder = 'of';
}
var location = $("#location").val();
var sortFilter = $("#sortFilter").val();
/* declare an checkbox array */
var HighlightsArrays = [];
/* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
$(".Highlights:checked").each(function() {
HighlightsArrays.push($(this).val());
});
/* we join the array separated by the comma */
var selectedHighlights;
selectedHighlights = HighlightsArrays.join(',') + ",";
if (FilterByOrder == '' || location == '' || sortFilter == '' || Highlights == '')
{
$.get('actionfilter.php', function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
else
{
$.get('actionfilter.php', {FilterByOrder: FilterByOrder, location: location, sortFilter: sortFilter, selectedHighlights: selectedHighlights}, function(data){
$('.disFilter').html(data).fadeIn("2000");
});
}
});
});
<script language="JavaScript">
function toggle() {
if($("#check-buton").prop("checked") == true){
$('.chkall').prop('checked', true);
}else{
$('.chkall').prop('checked', false);
}
}
$('#industry').click(function(){
if($('#s').val().trim())
{
window.location.href= '<?php echo base_url();?>search?industry_id='+$('#industry_id').val().trim()
}else{
$('#alert_error').text('Please Select Industry').show();
return false;
}
});
</script>
<div class="loginAccount">
<form method="post" name="search" action="<?php echo base_url();?>search">
<h3>Search by Industry :</h3>
Select All: <input type="checkbox" name="industry_id[]" id="check-buton" value="" onclick="toggle()">
<ul class="searchbyindustry">
<?php
if($Industries)
{?>
<?php
foreach($Industries as $Industry)
{
?>
<li> <input type="checkbox" name="industry_id[]" class="chkall" value="<?php echo $Industry['id'];?>"> <?php echo $Industry['industry_name'];?>
</li> <?php
} }
?>
<br/>
<br/>
<!-- <button type="button" id="industry">Search</button>-->
<input type="submit" name="submit" value="Search">
</ul>
</form>
<?php
if(_inputPost('industry_id'))
{
$ind=implode(',', _inputPost('industry_id'));
//print($ind);die;
$ind=ltrim($ind,',');
$industry_id = $ind;
$flag = true;
$condition = ' and sector in ('.$ind.')';
$extraparams = '?industry_id='.$industry_id;
}else if(_inputGet('industry_id'))
{
$ind= _inputGet('industry_id');
//print($ind);die;
$ind=ltrim($ind,',');
$industry_id = $ind;
$flag = true;
$condition = ' and sector in ('.$ind.')';
$extraparams = '?industry_id='.$industry_id;
}
else if(trim(_inputGet('s')))
{
$s = trim(_inputGet('s'));
$flag = true;
$condition = ' and (name LIKE '.$this->db->escape('%'.$s.'%').' or mobile_office LIKE '.$this->db->escape('%'.$s.'%').' or mobile2 LIKE '.$this->db->escape('%'.$s.'%').' or email2 LIKE '.$this->db->escape('%'.$s.'%').")";
$extraparams = '?s='.$s;
}
every type i run this it calls the error: OnError function and i can't see why it doesn't call the success: OnSuccess,
JS:
$(document).ready(function () {
// retreving data on button click
$("#data-submit").click(LoadDataThroughAjaxCall);
//loading screen functionality - this part is additional - start
$("#divTable").ajaxStart(OnAjaxStart);
$("#divTable").ajaxError(OnAjaxError);
$("#divTable").ajaxSuccess(OnAjaxSuccess);
$("#divTable").ajaxStop(OnAjaxStop);
$("#divTable").ajaxComplete(OnAjaxComplete);
//loading screen functionality - this part is additional - end
});
// ajax call
function LoadDataThroughAjaxCall() {
$.ajax({
type: "POST",
url: "Ajax/dataloader.php",
data: '{}',
dataType: "json",
success: OnSuccess,
failure: OnFailure,
error: OnError
});
// this avoids page refresh on button click
return false;
}
// on sucess get the xml
function OnSuccess(response) {
//debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var tweets = xml.find("Table");
showOnATable(tweets);
}
// show data on a table
function showOnATable(tweets) {
//debugger;
var headers = [];
var rows = [];
// header section
headers.push("<tr>");
headers.push("<td><b>tweets</b></td>");
headers.push("<td><b>created</b></td>");
headers.push("<td><b>source</b></td>");
headers.push("</tr>");
// rows section
$.each(tweets, function () {
var tweets = $(this);
rows.push("<tr>");
rows.push("<td>" + $(this).find("tweet_text").text() + "</td>");
rows.push("<td>" + $(this).find("created_at").text() + "</td>");
rows.push("<td>" + $(this).find("source").text() + "</td>");
rows.push("</tr>");
});
var top = "<table class='gridtable'>";
var bottom = "</table>";
var table = top + headers.join("") + rows.join("") + bottom;
$("#divTable").empty();
$("#divTable").html(table);
}
// loading screen functionality functions - this part is additional - start
function OnAjaxStart() {
//debugger;
//alert('Starting...');
$("#divLoading").css("display", "block");
}
function OnFailure(response) {
//debugger;
alert('Failure!!!' + '<br/>' + response.reponseText);
}
function OnError(response) {
//debugger;
var errorText = response.responseText;
alert('Error!!!' + '\n\n' + errorText);
}
function OnAjaxError() {
//debugger;
alert('Error!!!');
}
function OnAjaxSuccess() {
//debugger;
//alert('Sucess!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxStop() {
//debugger;
//alert('Stop!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxComplete() {
//debugger;
//alert('Completed!!!');
$("#divLoading").css("display", "none");
}
PHP:
<?php
//if(isset($_POST['data'])==true&&empty($_POST['data'])==false){
require_once('../connection.php');
function clean($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
//Sanitize the POST values
//$username = clean($_POST['data']);
//$result=sqlsrv_query($conn,"execute sp_ORDER_BY_name '$username'");
$result=sqlsrv_query($conn,"select tweet_text,source from tweets");
if($result) {
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
echo $row['tweet_text'].", ".$row['source']."<br />";
}
}else {
//Login failed
echo 'Name not found';
}
}
//}
?>
HTML FORM:
</head>
<body>
<div id="banner">
<h1>P-CAT version 0.1</h1>
</div>
<div id ="content">
<h2>Sreach Catigroies</h2>
<select id="data2">
<option value="">Plece select one of the follwing</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input name="data" id="data" type="text" />
<input type="submit" id="data-submit" value="Grab">
<div id="divTable">
</div>
</div>
<div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
text-align: left;">
<span>
<img src="Images/ajax-loader.gif" alt="Image not found." /></span>
<br />
<span style="text-align: left; padding-left: 8px;">Loading ...</span>
</div>
<div id="navbar">
<input type="button" value="EDIT">
<input type="button" value="HISTORY">
<input type="button" value="SETTINGS">
<input type="button" value="SEARCH">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/global.js"></script>
</body>
You have to response a json from php like,
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
$xml='<Table>';
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
$xml.='<tweet_text>'.$row['tweet_text'].'</tweet_text>';
$xml.='<source>'.$row['source'].'</source>';
// create xml tag for created_at
}
$xml.='</Table>';
echo json_encode(array('d'=>$xml));
return TRUE;
} else {
//Login failed
echo json_encode(array('d'=>'Name not found'));
}