I'm trying to get it so when a button is pressed it runs a PHP function without reloading the page.
I have this button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button>Reserve Book</button>
</div>
Which I want to run:
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reserbook.php', 'book_id');
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
</script>
The PHP file is, reservebook.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);
}
?>
The js runs fine and makes the modal box fade then out displaying the variable passed to it, I just don't know how to get the post working.
I've been trying to udnerstand looking at other answers on questions such as calling php function from jquery? and How to pass jQuery variables to PHP variable?
I'm also not sure if I need a ajax specific script to be called at the start as right now all I have is
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
for my jquery.
It is probably something very simply, a rookie mistake, so all help is appreciated.
<script>
//called when button is clicked
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
//set parameter which you want to pass, url to be requested
$.ajax({ url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function(result) {
//after success it will be here and server have to send some data to be handled
alert(result);
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
What are you posting to reservebook.php? book_id is a string.You should send data in json or xml format to the server or using a query like key1=value1&key2=value2. $.post is a shortcut function i think it's better to use $.ajax and specify the type attribute POST.
You have to add a parameter to the post function to get the postdata in your php
{ jqbookID: book_id }
Try this :
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.post('reservebook.php', { jqbookID: book_id }, function() {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
});
});
Related
I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});
I want to reload some data from .txt files.
The .txt files looks like this:
0;Player 1;10;Player 2;10;Player 3;0;Player 4;0;00:00:00;0;0
I tryed to reload the data "10" after Player 1 which had the PHP Value $s1s[2].
Following Code does read the whole txt file (I know), but I am not familiar with Javascript and I need to get the output of this single Value instead of the whole txt file.
PHP:
$spielfile = "data/$v/source.txt";
Javascript:
$(document).ready(function() {
setInterval(function() {
var randomnumber=Math.floor(Math.random()*100)
$("<?php echo "#staende_$v" ?>").load("<?php print $spielfile ?>");
}, 1000);
});
Any suggestion how I can do this?
you could search the string using a regex:
$(document).ready(function() {
setInterval(function() {
$.get(
"<?= $spielfile ?>",
{ "_": $.now() }, // disable response cache, multiple methods available.
function(data) {
var val = data.replace(/.*;Player 1;([0-9]+).*/, '$1');
$("#staende_<?= $v ?>").text(val);
}
);
}, 1000);
});
As Rory McCrossan mentions, you should be using an Ajax request returning data in JSON.
$(document).ready(function() {
setInterval(function() {
$.get(
"yourscript.php",
{ "_": $.now() }, // disable response cache, multiple methods available.
function(data) {
data.forEach(function(player){
$('<?= "#staende_$v" ?>').text("Player: " + player.id + " has data " + player.data);
})
}
);
}, 1000);
});
Your PHP should obviously load the text file, fetch the desired data and return in correct format:
<?php
$content = file_get_contents('./source.txt');
$content = explode(';', $content);
// The array should look like this for the js to function:
$data[] = [
'id' => 1,
'data' => $content[2]
];
// You can append more data for other players as well, easy to loop through in JS.
die(json_encode($data));
?>
There was also a little problem with browser cache, the second param in the $.get request would resolve that. You can do "<?= $spielfile ?>?time="+$.now() instead of using the second param.
Actually i want to refresh my content of a page without Refreshing the whole page through JavaScript or j Query ....... and i did my whole project into ( Php or javaScript) so i face such type of problem
Note : i want to refresh my page content when user do some action
Here is my Code:
//On Button click, the below will be execute:
$('body').on('click', '#click', loadDoc);
and the LoadDoc functio:
function loadDoc() {
//alert('heruybvifr');
var _this = $(this);
var order_id= $(this).parents('.modal').find('.order-id').text();
$.get('myPHP.php',{order_id: order_id},function(){
_this.hide();
})
}
Now myPHP.php :
<?php
include("connection.php");
$limit = intval($_GET['order_id']);
echo $valuek;
$query="UPDATE orders
SET status ='cooking'
WHERE id = $limit";
if (mysqli_query($connection,$query)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($connection);
}
?>
Yes you can use the jQuery.ajax() call. Like this:
Change the text of a element using an AJAX request:
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
}});
});
See this tutorial for more information:
http://www.w3schools.com/jquery/ajax_ajax.asp
You can use JQuery Ajax functions to accomplish your requirement.
all there functions given below will work for loading the content without refreshing the page.
$.post("/controller/function", params, function(data) {
// set received data to html
});
$.ajax("/controller/function", params, function(data) {
// set received data to html
});
$.get("/controller/function", params, function(data) {
// set received data to html
});
You can load the data from the server and and place the returned HTML into the matched element.
<div id="content"></div>
$("#content").load( "ajax/test.html" );
I'm trying to make a CRUD in jquery/ajax/php for learning purposes.
But I can't figure out what I'm doing wrong with the delete part.
My goal is to delete an record from the database without refreshing the page.
Ajax function:
$(document).on('click', '.deleteOrder', function(e){
var id = $(this).attr('id');
console.log('Clicked order: ' + id);
$.ajax({
type: 'POST',
url: 'orders/deleteorder/',
data: {
orderId: id
},
success: function(data){
updateOrder(e);
},
error: function(){
console.log('error');
}
});
});
Php function:
public function deleteOrder(){
$orderId = $_POST['id'];
$count=$this->connection->prepare("DELETE FROM orders WHERE orderNumber = :number");
$count->bindParam(":number",$orderId,PDO::PARAM_INT);
$count->execute();
echo 'Finished order ' . $orderId;
}
First check the delete function called or not through ajax, in browser Network tab (you see this when clicking F12 button in browser)
you did not call deleteOrder function .
Tab 1 does not work. Tab 1 is drawn from MySQL table. I want show default tab and add or delete an extra tab and post mysql get inserted tab id append not count?. Can you help?
Visit jsfiddle jsfiddle.net/datakolay/33aM3/
Html
<ul id="tabul">
<li id="litab" class="ntabs add">+</li>
<li id="t21" class="ntabs"> Tab Mysql id 21
×
</li>
<li id="t22" class="ntabs"> Tab Mysql id 22
×
</li>
</ul>
<div id="tabcontent">
<p id="c21">Test</p>
<p id="c22">Test</p>
</div>
Javascript
$(function() {
var total_tabs = 0;
total_tabs++;
$("#addtab, #litab").click(function() {
total_tabs++;
$("#tabcontent p").hide();
addtab(total_tabs);
return false;
});
function addtab(count) {
var closetab = '×';
$("#tabul").append('<li id="t'+count+'" class="ntabs">Tab Extra '+closetab+'</li>');
$("#tabcontent").append('<p id="c'+count+'">Tab Content </p>');
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#t"+count).bind("click", function() {
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+count).fadeIn('slow');
});
$("#close"+count).bind("click", function() {
// activate the previous tab
$("#tabul li").removeClass("ctab");
$("#tabcontent p").hide();
$(this).parent().prev().addClass("ctab");
$("#c"+count).prev().fadeIn('slow');
$(this).parent().remove();
$("#c"+count).remove();
return false;
});
}
});
MY NEW EDİT
Visit jsfiddle jsfiddle.net/datakolay/33aM3/8/
$(function() {
$('#tabcontent p').hide().filter(':lt(1)').show();
$("#tabul li").removeClass("ctab");
$(".ntabs").filter(':lt(1)').addClass("ctab");
$("#addtab").click(function() {
$("#tabcontent p").hide();
var dataString = '';
$.ajax({
type: "POST",
url: "add_tab.php",
data: dataString,
cache: false,
success: function(html)
{
$("#tabul li").removeClass("ctab");
$("#t"+count).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+count).fadeIn('slow');
}
});
return false;
});
$(".ntabs").bind("click", function() {
var id = $(this).attr('id')
$("#tabul li").removeClass("ctab");
$(".ntabs").addClass("ctab");
$("#tabul li").removeClass("ctab");
$("#"+id).addClass("ctab");
$("#tabcontent p").hide();
$("#c"+id).fadeIn('fast');
});
$(".close").bind("click", function() {
var id = $(this).attr('id')
$("#tabul li").removeClass("ctab");
$("#tabcontent p").hide();
$(this).parent().prev().addClass("ctab");
$("#c"+id).prev().fadeIn('fast');
$(this).parent().remove();
$("#c"+id).remove();
return false;
});
You're only adding the event listener to dynamically added tabs i.e.; tab 2, tab 3, tab 4... since tab 1 is hardcoded into the html opposed to being dynamically loaded in, it's never getting the listener added. Although there are a ton of optimizations I'd add to this, the quick fix is to add.
$("#t1").bind("click", function() {
$("#tabul li").removeClass("ctab");
$("#t1").addClass("ctab");
$("#tabcontent p").hide();
$("#c1").fadeIn('slow');
});
I believe your problem is in fact in your HTML not your JQuery. It appears to work properly (as far as I can tell) if you modify your html from this:
<ul id="tabul">
<li id="litab" class="ntabs add">+
<li id="t1" class="ntabs"> Tab 1×</li>
</li>
</ul>
<div id="tabcontent">
<p id="c1">Test</p>
</div>
To this:
<ul id="tabul">
<li id="litab" class="ntabs add">+</li>
</ul>
<div id="tabcontent">
</div>
Then, I'd make a small adjustment to your JQuery, change:
var total_tabs = 1;
to:
var total_tabs = 0;
Next, you'd need to work on the way your JQuery handles closing tabs. If the first tab is closed, the '+' tab is displayed. If a tab is closed that's not currently focused, it changes focus to the previous tab of the closed tab.
JSFiddle with my suggestions.
Edit: I also thought I'd present one more thing. My assumption is that you're going to have some way to dynamically add content to these tabs; given that, I'd dynamically add the first tab (like my suggestion would do) instead of hard coding it into the html simply due to the fact that your JQuery already works for tabs dynamically added (meaning you're doing something wrong with adding listeners to the static tab). Just my two cents.
Edit 2: To answer your question about how to access your MySQL data from JQuery, you should really google something like JQuery get data from MySQL database. That said, you've added PHP to the tags, so we'll assume that's what you want to use. You need to construct an AJAX call through JQuery to retrieve the information. Also, you need a PHP script to interact with the server.
PHP Script:
<?PHP
$db_address = 'localhost';
$db_user= 'root';
$db_pass= 'password';
$db_name= 'TabData';
$db;
function connect() {
global $db, $db_server, $db_user, $db_password, $db_dbname;
if (!$db) {
$db = mysql_connect($db_server, $db_user, $db_password);
}
if (!$db) {
die('Could Not Connect: ' . mysql_error());
} else {
mysql_select_db($db_dbname);
}
}
function disconnect() {
global $db;
if ($db) {
mysql_close($db);
}
}
function query($query) {
global $db;
if (!$db) {
connect();
if ($db) {
return query($query);
}
} else {
$result = mysql_query($query);
return $result;
}
}
function getTabData($id) {
$result = query("SELECT * FROM tabs WHERE id = \"".$id."\"");
}
$data = array();
$json = file_get_contents('php://input'); // read JSON from raw POST data
if (!empty($json)) {
$data = json_decode($json, true); // decode
if(isset($data["id"]) && !empty($data["id"])) {
connect();
getTabData($data["id"]);
disconnect();
}
?>
Basically, that code will connect to a database named TabData and return in JSON the information from the row in table tabs with an ID matching that passed in the AJAX query.
JQuery for creating an AJAX call to the above PHP code (contained in a file named myPHP.php):
function updateTab(tabID) {
$.ajax({
type: "POST",
url: "/myPHP.php",
contentType: "application/json",
data: JSON.stringify({id: tabID}),
success: function (data) {
var tabData = $.parseJSON(data);
$.each($.parseJSON(data), function() {
$("#c" + this.id).html("" + this.info);
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + "\nXMLHttpRequest status: " + XMLHttpRequest.status + "\nXMLHttpRequest statusText: " + XMLHttpRequest.statusText + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown);
}
});
}
Basically, that code will connect to a php script named myPHP.php and send an AJAX query with the ID of the passed in ID. Upon successful return of the request, the success function will return, which parses the returned data from the PHP script and updated the content page of the appropriate id. I haven't tested this code (since I don't have a readily available environment); but it is code that I have slightly modified from some of my existing code (thus, it should work without too many adjustments).