i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location.
I am able to seacrh when user enters name in the search box(tab-1).
In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.
First time with Ajax, any help would be highly appreciated.
AJAX script:
$(document).ready(function () {
$("#search_results").slideUp();
$("#button_find").click(function (event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function (event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("search.php", {
searchit: search_this
}, function (data) {
$("#display_results").html(data);
})
}
html:
<form id="searchform" method="post">
<input id="search_query" name="search_query" placeholder="What You Are Looking For?"
size="50" type="text" />
<input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>
<div class="tab">
<input id="tab-2" name="tab-group-1" type="radio" />
<label for="tab-2">Search by Category</label>
<div class="content">
<div id="searchbycategory">
<div id="nav_1_a">
<ul>
<li>All Categories</li>
<li>Category-1</li>
<li>Category-2</li>
<li>Category-3</li>
</ul>
<div id="display_results">
</div>
</div>
<!-- END nav_1_a -->
</div>
</div>
</div>
<div class="tab">
<input id="tab-3" name="tab-group-1" type="radio" />
<label for="tab-3">Search by location</label>
<div class="content">
<div id="searchbylocation">
<div id="nav_1_a">
<ul>
<li>All</li>
<li>Location-1</li>
<li>Location-2</li>
<li>Location-3</li>
<li>Location-4</li>
</ul>
</div>
search.php:
<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term);
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like
'{$term}%'", $connection);
echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
echo "" . $info['col2'] . "";
echo "</li>";
}
}else{
echo "No matches found!";
}
echo "</ul>";
}
?>
Pass block id to search_ajax_way function:
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way(this.id);
});
Then pass block id in data param in ajax request:
function search_ajax_way(blockId){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
$("#display_results").html(data);
})
}
Now blockId will be availible in your php script as $_POST['blockId'].
You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:
$("a").click(function (event) {
event.preventDefault();
search_ajax_way(this.id);
});
function search_ajax_way(clickedId) {
$("#search_results").show();
var postData = { searchit: $("#search_query").val() };
if (clickedId) {
postData.clickedId = clickedId;
}
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
The id will be available in PHP as $_POST['clickedId']
Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:
$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);
function search_ajax_way(event) {
event.preventDefault();
$("#search_results").show();
var postData = {
searchit: $("#search_query").val(),
clickedId: this.id
};
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
Related
This is controller.php
<?php
class Autocomplete extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('datacomplete');
}
public function index($id)
{
echo $id;
$this->load->view('view_demo', $data);
}
public function GetCountryName()
{
$keyword = $this->input->post('keyword');
$data = $this->datacomplete->GetRow($keyword);
echo json_encode($data);
}
}
?>
This is a model
<?php
class Datacomplete extends CI_Model
{
public function GetRow($keyword)
{
$this->db->order_by('id', 'DESC');
$this->db->like("name", $keyword);
return $this->db->get('autocomplete')->result_array();
}
}
this is view.php
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js">
</script>
<script src="<?php echo base_url(); ?>assets/custom.js">
</script>
</link>
</head>
<body style="background-color: #000000;">
<?php echo $id= 1; ?>
<form action="<?php echo base_url('autocomplete/index/' .$id); ?>" method="post">
<div class="row">
<center>
<h2 style="color: #fff;">
AUTOCOMPLETE FORM FROM DATABASE USING CODEIGNITER AND AJAX
</h2>
</center>
<div class="col-md-4 col-md-offset-4" style="margin-top: 200px;">
<label class="control-lable" style="color: #fff;">
Country Name
</label>
<input autocomplete="off" class="form-control" id="country" name="country" placeholder="Type to get an Ajax call of Countries" style="height:70px" type="text">
<ul aria-labelledby="dropdownMenu" class="dropdown-menu txtcountry" id="DropdownCountry" role="menu" style="margin-left:15px;margin-right:0px;">
</ul>
<input type="submit">
</input>
</input>
</div>
</div>
</form>
</body>
</html>
This is custom.js file
$(document).ready(function() {
$("#country").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/codeajax/autocomplete/GetCountryName",
data: {
keyword: $("#country").val()
},
dataType: "json",
success: function(data) {
if (data.length > 0) {
$('#DropdownCountry').empty();
$('#country').attr("data-toggle", "dropdown");
$('#DropdownCountry').dropdown('toggle');
} else if (data.length == 0) {
$('#country').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" class="dropdownlivalue">' + value['name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#country').val($(this).text());
});
});
I want to fetch the id of the country dynamically in the URL after clicking the submit button.
Now I have this using static passing id as 1.
the table has two column id and name of the country.
how to pass the id dynamically to url when I click the submit button.
I m failing to fetch the id dynamically from database ie when I click on submit should redirect to the new page with country id or echo $id in the new page as well as to the URL it should show me id of the country
You could achieve it using javascript.
First change the form :
<form action="<?php echo base_url('autocomplete/index/' .$id); ?>" method="post">
To :
<form method="post" id="countryForm">
Then change the submit button :
<input type="submit">
To :
<input type="submit" id="submitForm" disabled>
And then apply the following javascript codes :
$(document).ready(function() {
$("#country").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/codeajax/autocomplete/GetCountryName",
data: {
keyword: $("#country").val()
},
dataType: "json",
success: function(data) {
if (data.length > 0) {
$('#DropdownCountry').empty();
$('#country').attr("data-toggle", "dropdown");
$('#DropdownCountry').dropdown('toggle');
} else if (data.length == 0) {
$('#country').attr("data-toggle", "");
}
// Assign each country id into each country list `data-` element
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCountry').append('<li role="displayCountries" ><a role="menuitem dropdownCountryli" data-countryid="' + value['id'] + '" class="dropdownlivalue">' + value['name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#country').val($(this).text());
$('#countryForm').attr('action', '<?php echo base_url('autocomplete/index/'); ?>' + $(this).data('countryid'); // set new form action which contain country id
$('#submitForm').removeAttr('disabled'); // enable the submit button after one country is selected
});
});
I'm creating a website where the user is supposed to check a couple of checkboxes and then the site will present the data in a table.
I have been looking at this "guide", but cant make it work on my page. I get no results on my index.php, and the submit.php just shows "Array[]"
This is what I have so far:
Index.php holds the checkboxes and the jQuery script.
Checkboxes is in a drop down menu, like this:
<div id="menu">
<div id="mainmenu">Gender</div>
<div id="submenu1" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="male">Male</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="female">Female</a></div>
</div>
<div id="mainmenu">Price range</div>
<div id="submenu2" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="200">200-299$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="300">300-399$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="400">400-499$</a></div>
</div>
jQuery script:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function makeTable(data){
console.log(data);
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getSnowboardFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.id);
}
});
return opts;
}
function updateSnowboards(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#boards tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getSnowboardFilterOptions();
updateSnowboards(opts);
});
checkboxes.trigger("change");
</script>
At last I have submit.php, which holds the php code for selecting the right stuff.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=...', '...', '...');
$opts = $_POST['filterOpts'];
$qMarks = str_repeat('?,', count($opts) - 1) . '?';
$statement = $pdo->prepare("SELECT gender, price_range, brand, model, rocker_type, flex, size_range, image FROM snowboards)");
$statement -> execute($opts);
$results = $statement -> fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
Right now the SELECT query isn't specified, because I don't know how.
If someone knows what I'm doing wrong, or have better suggestion to solve it, please tell.
I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>
I'm using the jquery validator plugin, and I'm trying to make my first attempt with AJAX to it.
Right now, I have the following HTML code:
<div class="grid_12" id="info">
</div>
<div class="grid_12">
<div class="block-border">
<div class="block-header">
<h1>Inserir nova página</h1><span></span>
</div>
<form id="formulario" class="block-content form" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<div class="_100">
<p><label for="textfield">Nome da página</label><input id="page_name" name="textfield" class="required text" type="text" value="" /></p>
</div>
<div class="_100">
<p><label for="textarea">Conteúdo da página</label><textarea id="page_content" name="textarea" class="required uniform" rows="5" cols="40"></textarea></p>
</div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-validate-form" href="javascript:void(0);">Limpar</a></li>
</ul>
<ul class="actions-right">
<li><input type="submit" class="button" name="send" value="Inserir"></li>
</ul>
</div>
And my JS code:
<script type="text/javascript">
$().ready(function() {
/*
* Form Validation
*/
$.validator.setDefaults({
submitHandler: function(e) {
$.jGrowl("Ação executada com sucesso.", { theme: 'success' });
$(e).parent().parent().fadeOut();
/*
* Ajax
*/
var mypostrequest=new ajaxRequest();
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("info").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request")
}
}
}
var page_name=encodeURIComponent(document.getElementById("page_name").value);
var page_content=encodeURIComponent(document.getElementById("page_content").value);
var parameters="page_name="+page_name+"&page_content="+page_content;
mypostrequest.open("POST", "ajax/inserir_utilizador.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
v.resetForm();
v2.resetForm();
v3.resetForm();
return false;
}
});
var v = $("#create-user-form").validate();
jQuery("#reset").click(function() { v.resetForm(); $.jGrowl("User was not created!", { theme: 'error' }); });
var v2 = $("#write-message-form").validate();
jQuery("#reset2").click(function() { v2.resetForm(); $.jGrowl("Message was not sent.", { theme: 'error' }); });
var v3 = $("#create-folder-form").validate();
jQuery("#reset3").click(function() { v3.resetForm(); $.jGrowl("Folder was not created!", { theme: 'error' }); });
var formulario = $("#formulario").validate();
jQuery("#reset-validate-form").click(function() { formulario.resetForm(); $.jGrowl("O formulário foi limpo!", { theme: 'information' }); });
});
I have a div #info without anything in it that I'm trying to put there the result of the ajax.
My ajax file is just trying to echo the POST values:
<?php
$page_name=$_POST["page_name"];
$page_content=$_POST["page_content"];
echo $page_name."<br />";
echo $page_content;
?>
But it really doesn't work. It really doesn't do anything, or if it does, it refreshes the page.
What am I missing?
Regards and thanks!
I recommend you to use $.ajax() or $.post().
It's much easier and your headache will surely go away.
$.ajax({
type: 'POST',
url: 'url to post',
data: data,
success: function(data, status) {
//callback for success
},
error: error, //callback for failure
dataType: "json" //or "html" etc
});
many examples here:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.ajax/
I'm trying to update a div with an ajax post. Problem is...it's updating every div.
Here's the json.php:
//json.php
$data['months'] = $db->escape_value($_POST['check']);
$data['id'] = $db->escape_value($_POST['hidden']);
$query = "UPDATE month SET months = '{$data['months']}' WHERE monthID = '{$data['id']}'";
$result = $db->query($query);
if($result) {
$data['success'] = true;
$data['message'] = "Update Successful!";
$data['text'] = $_POST['check'];
echo json_encode($data);
} else {
$data['message'] = "Update could not be completed.";
}
And the html:
<?php
$query = $db->query('SELECT * FROM month');
?>
<html>
<head>
<title>jQuery/Ajax - Update is updating all divs</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.check, button.save, input.cancel, div.message").hide();
$(".edit").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").hide();
$(this).parent().siblings("li.liThree").children("button.save").show();
$(this).parent().siblings("li.liFour").children("input.cancel").show();
$(this).parents("ul").siblings("div.showText").hide();
$(this).parents("ul").siblings("input.check").show();
$(this).hide();
return false;
});
$(".cancel").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").show();
$(this).parent().siblings("li.liThree").children("button.save").hide();
$(this).parent().siblings("li.liOne").children("input.edit").show();
$(this).parents("ul").siblings("div.showText").show();
$(this).parents("ul").siblings("input.check").hide();
$(this).hide();
return false;
});
$("form[name=form1]").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText").html(data.text);
$(".message").html(data.message).slideDown("fast");
$(".check").hide();
$("button.save").hide();
$(".cancel").hide();
$(".edit").show();
$(".delete").show();
$(".showText").show();
return false;
}
}, "json");
return false;
});
});
</script>
</head>
<body>
<div class="message">message</div>
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
<div class="container">
<div class="showText"><?php echo $row['months']; ?></div>
<input name="check" type="text" class="check" value="<?php echo $row['months']; ?>" />
<input name="hidden" type="hidden" class="hidden" value="<?php echo $row['monthID']; ?>" />
<ul class="list">
<li class="liOne">
<input name="edit" type="button" class="edit" value="edit" />
</li>
<li class="liTwo">
<input name="delete" type="submit" class="delete" value="delete" />
</li>
<li class="liThree">
<button name="save" type="submit" class="save" value="<?php echo $row['monthID']; ?>">save</button>
</li>
<li class="liFour">
<input name="cancel" type="button" class="cancel" value="cancel" />
</li>
</ul>
</div>
</form>
<?php } ?>
<!--<a id="reset" href="test3.php">reset</a>-->
</body>
</html>
You need to specify a context (the form) for the elements you're changing:
$("form[name=form1]").submit(function(){
var form = this;
var params = $(this);
$.post(form.action, { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText", form).html(data.text);
$(".message", form).html(data.message).slideDown("fast");
$(".check", form).hide();
$("button.save", form).hide();
$(".cancel", form).hide();
$(".edit", form).show();
$(".delete", form).show();
$(".showText", form).show();
return false;
}
}, "json");
return false;
});
Also, if you hide a parent element, the children are hidden, too, so you probably want to do that...
Every div has the same class: showText. They need unique IDs instead, like Div1, Div2. Then update them by their ID: $("#Div1")
Hint, instead of answer:
How many elements does $(".showText") return?
2nd Hint: It's more than one!
===
Edit for more clarity:
The first issue is that you're selecting by classes like .showText. But you're creating multiple forms, each of which has an element that matches .showText. You need some way to point at the right element in each form. One way to solve this is to add an ID on each FORM tag, so you can then select things like $('#form-number-$N .showtext) -- which selects any elements with class="showtext" inside the element with id "#form-number-$N"
You're looping over rows in your database and writing the forms. So you need some variable data to identify each individual form.
You've got a while loop that populates $row:
<?php while($row = $db->fetch_assoc($query)) { ?>
But currently, every form you create has a name attribute of "form1".
So what if, instead of:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
You did something like:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form<?PHP echo $row['id']; ?>" id="<?PHP echo $row['id']; ?> class="myFormClass" method="post">
Then you could use a handler that looks something like:
$("form.myFormClass").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(this.id + " .showText").html(data.text);
...
return false;
}
}, "json");
return false;
});
Do you see what's happening there?