This is the php file containing the new content, to replace .hotels when the form is submitted.
<?php
if(isset($_POST['submit'])){
$pdo = new PDO('mysql:host=localhost;dbname=CSV_DB', 'root', 'root');
$inputType = $_POST['type'];
$inputCategory = $_POST['category'];
$type = $pdo->query("SELECT * FROM Hotels WHERE Type LIKE '%$inputType%' AND Price_Range= '$inputCategory'");
foreach($type as $row){
echo"<div id='newHotels'>";
echo "<div class='hotelImage'></div>";
echo'<h4>'.$row['Hotel_Name']." ".$row['Rating']."*".'</h4>'." ".'<p>'.$row['Description'].'</p>'." "."Location: ".$row['Location']." ".'<h4 style="font-weight: bold">'."£".$row['Price']."p/p".'</h4>';
echo "</div>";}
}
?>
Here is the original div that displays all the hotels in the database when the page loads and that I want to replace with the new content when the form is submitted:
<div id="hotels">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=CSV_DB', 'root', 'root');
$display = $pdo->query('SELECT Hotel_Name, Description, Location, Rating, Price FROM Hotels');
foreach ($display as $row){
if($row)
echo"<div id='hotel'>";
echo "<div class='hotelImage'></div>";
echo'<h4>'.$row['Hotel_Name']." ".$row['Rating']."*".'</h4>'." ".'<p>'.$row['Description'].'</p>'." "."Location: ".$row['Location']." ".'<h4 style="font-weight: bold">'."£".$row['Price']."p/p".'</h4>';
echo "</div>";}
?>
</div>
And here is the Ajax that is supposed to change the content
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'form.php',
data: $('form').serialize(),
success: function(data) {
$(".hotels").html(data);
}
});
});
});
I need help replacing the contents of .hotels with the search results of my form when the form submits however the div just becomes empty. I think I need to make data equal to the search results but not sure how to go about it.
submitted the console log says data is not defined.
You need to define data in the success function.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'form.php',
data: $('form').serialize(),
success: function(data) { /* you missed variable data here */
$("#hotel").html(data);
}
});
});
});
The console log saying "data" is not defined means there is no variable named "data". to solve this issue, you could either create a global variable called "data", or pass "data" as an argument to the success function. This would then look somewhat like this:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'form.php',
data: $('form').serialize(),
success: function(data) {
$("#hotel").html(data);
}
});
});
});
Related
What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
I have a button which calls a modal box to fade into the screen saying a value posted from the button then fade off, this works fine using jquery, but I also want on the same click for value sent from the button to be posted to a php function, that to run and the modal box to still fade in and out.
I only have this to let my site know what js to use:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
I'm still new so sorry for a rookie question, but will that allow ajax to run, or is it only for jquery?
The current script I'm trying is: (Edited to be correctly formed, based on replies, but now nothing happens at all)
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.ajax
({
url: 'reservebook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
Though with this the modal box doesn't even happen.
The php is, resersebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
and to be thorough, the button is:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>"><button>Reserve Book</button></div>
I'm new to this and I've looked at dozens of other similar questions on here, which is how I got my current script, but it just doesn't work.
Not sure if it matters, but the script with just the modal box that works has to be at the bottom of the html body to work, not sure if for some reason ajax needs to be at the top, but then the modal box wouldn't work, just a thought.
Try this. Edited to the final answer.
button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button class="reserve-button">Reserve Book</button>
</div>
script:
<script>
$('.reserve-button').click(function(){
var book_id = $(this).parent().data('id');
$.ajax
({
url: 'reservebook.php',
data: {"bookID": book_id},
type: 'post',
success: function(result)
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
reservebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['bookID']))
{
$bookID = $_POST['bookID'];
$result = mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
if ($result)
echo "Book #" + $bookId + " has been reserved.";
else
echo "An error message!";
}
?>
PS#1: The change to mysqli is minimal to your code, but strongly recommended.
PS#2: The success on Ajax call doesn't mean the query was successful. Only means that the Ajax transaction went correctly and got a satisfatory response. That means, it sent to the url the correct data, but not always the url did the correct thing.
You have an error in your ajax definitions. It should be:
$.ajax
({
url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
You Ajax is bad formed, you need the sucsses event. With that when you invoke the ajax and it's success it will show the response.
$.ajax
({
url: 'reserbook.php',
data: {"book_id":book_id},
type: 'post',
success: function(data) {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
}
Edit:
Another important point is data: "book_id="+book_id, that should be data: {"book_id":book_id},
$.ajax
({
url: 'reservebook.php',
data: {
jqbookID : book_id,
},
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
Try this
I am new to using ajax and I am having trouble with posting variables and accessing those variables in my controllers.
Here is the Controller Code
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
/* $this->load->model('product_model');
$q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
$data = $this->product_model->get_record_specific($q);
echo json_encode($data[0]->quantity);
*/
echo $product;
}
function index()
{
$this->load->view('autocomplete_view');
}
}
If I change the echo to a string inside single quotes like this 'Hello World', it will return the hello world back to the view correctly. But it will not do the same if I try it as it currently is. Also if I use echo json_encode($product); it then returns false.
Here is view code with ajax.
$( document ).ready(function () {
// set an on click on the button
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: 'productName',
success: function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<h1> Get Data from Server over Ajax </h1>
<br/>
<button id="button">
Get posted varialbe
</button>
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
//echo $product;
//in ajax dataType is json -here You have to return json data
echo json_encode($product);
}
...
}
//javascript file
var productName = $('#productName).val();//get value of product name from form
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: {productName:productName},//You have to send some data from form
success: function(msg){
alert(msg);
}
});
I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call
My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.