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
Related
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);
}
});
});
});
As i'm building an website that needs Ajax for sending POST methods without refreshing the entire page.
I tried using ajax to send data from an onclick event on an LINK-tag, but the ajax code does seem to send an EMPTY post.
This is the php/jquery/ajax code:
<p id="school_content">
</p>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
contentType: "application/json; charset=utf-8",
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
},
});
$("#school_content").load("id_script.php");
});
});
</script>
The LINK-tag has the 'id' of the school of wich the information needs to be shown in the PARAGRAPH with 'id' "school_content" by this jquery part: $("#school_content").load("id_script.php"); .
The var Id = $(this).attr('id'); part works, because he's giving me the right school_name in an alert(); if I ask it to.
The id_script.php needs to get this POST in the usual way, but is does not..
The id_script.php code:
<?php
include('connect.php');
header('Content-Type: application/json');
if(isset($_POST['school_name'])){
$Id = $_POST['school_name'];
$extract = mysqli_query($con, "SELECT * FROM school_kaart WHERE school_name='$Id'");
$numro=mysqli_num_rows($extract);
if(mysqli_num_rows($extract) == '1'){
$row = mysqli_fetch_assoc($extract);
echo 'Yes it works!';
}
else{
echo 'Nope, didnt work!';
}
}
else{
echo 'Not posted!';
}
?>
I'm still getting "Not posted!" in the PARAGRAPH I mentioned earlier. What seems to be the problem?
.load is shorthand for an ajax request so you are actually doing 2 request.
The latter isn't sending any data and so it returns 'Not Posted!';
http://api.jquery.com/load/
try
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
$("#school_content").html(data);
},
});
//remove this
//$("#school_content").load("id_script.php");
});
});
</script>
i want to delete a row of data in my sql when delete button is pressed in xdk. i searched for some codes but still doesnt delete the data.
this is the php file (delete.php)
<?php
include('dbcon.php');
$foodid = $_POST['foodid'];
$query = "DELETE FROM menu WHERE id ='$foodid'";
$result=mysql_query($query);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
and now here is my ajax code.
$("#btn_delete").click( function(){
alert("1");
var del_id = $(this).attr('foodid');
var $ele = $(this).parent().parent();
alert("2");
$.ajax({
type: 'POST',
url: 'http://localhost/PHP/delete.php',
data: { 'del_id':del_id },
dataType: 'json',
succes: function(data){
alert("3");
if(data=="YES"){
$ele.fadeOut().remove();
} else {
alert("Cant delete row");
}
}
});
});
as you can see, i placed alerts to know if my code is processing, when i run the program in xdk. it only alerts up to alert("2"); . and not continuing to 3. so i assume that my ajax is the wrong part here. Im kind of new with ajax.
<?php
$sqli= "*select * from temp_salesorder *";
$executequery= mysqli_query($db,$sqli);
while($row = mysqli_fetch_array($executequery,MYSQLI_ASSOC))
{
?>
//"class= delbutton" is use to delete data through ajax
<button> Cancel</button>
<!-- language: lang-js -->
//Ajax Code
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
$.ajax({
type: "GET",
url: "deletesales.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
return false;
});
});
</script>
//deletesales.php
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'pos';
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
$id=$_GET['id']; <!-- This id is get from delete button -->
$result = "DELETE FROM temp_salesorder WHERE transaction_id= '$id'";
mysqli_query($db,$result);
?>
<!-- end snippet -->
A couple of things:
You should be testing using console.log() instead of alert() (imo)
If you open up your console (F12 in Google Chrome) do you seen any console errors when your code runs?
Your code is susceptible to SQL Injection, you will likely want to look into PHP's PDO to interact with your database.
Does your PHP file execute correctly if you change:
$foodid = $_POST['foodid'];
To
$foodid = 1
If number 4 works, the problem is with your javascript. Use recommendations in numbers 1 and 2 to diagnose the problem further.
Update:
To expand. There are a few reasons your third alert() would not fire. The most likely is that the AJAX call is not successful (the success handler is only called if the AJAX call is successful). To see a response in the event of an error or failure, you can do the following:
$.ajax({
url: "http://localhost/PHP/delete.php",
method: "POST",
data: { del_id : del_id },
dataType: "json"
})
.done(function( msg ) {
console.log(msg);
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
More information on AJAX and jQuery's $.ajax can be found here
My "best guess" is a badly formatted AJAX request, your request is never reaching the server, or the server responds with an error.
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 some JQuery handling a div click. If the div is clicked once it hides itself and shows another div (and posts to a php script in the background). If it is then clicked again, it's supposed to hide the new div, show the new one again, and post more data to a different script, and so on.
It changes the first time (.f hides, .uf shows) but when I click '.uf' nothing happens.
JQuery:
if($('.f').is(":visible")) {
$('#follow').click(function() {
var to_follow = $('.name').attr('id');
$.ajax({
type: "POST",
url: "/bin/rel_p.php",
data: "y=" + to_follow,
success: function() {
$('.f').hide();
$('.uf').show();
}
});
});
}
else {
$('#follow').click(function() {
var to_unfollow = $('.name').attr('id');
$.ajax({
type: "POST",
url: "/bin/relu_p.php",
data: "y=" + to_follow,
success: function() {
$('.uf').hide();
$('.f').show();
}
});
});
}
HTML:
<div id="follow" class="f">
<img src="img/icons/Follow.png">
<h1>Follow</h1>
</div>
<div id="follow" class="uf" style="display:none;">
<img src="img/icons/Unfollow.png">
<h1>Unfollow</h1>
</div>
use a class if you intend to use the selector twice, and don't write the same code twice unless you have to:
$('.follow').on('click', function() {
var is_f = $('.f').is(":visible"),
to_follow = $('.name').attr('id'),
give_me_an_u = is_f?'':'u';
$.ajax({
type: "POST",
url: "/bin/rel" + give_me_an_u + "_p.php",
data: {y : to_follow}
}).done(function() {
$('.f, .uf').toggle();
});
});