Probably a stupid question because I am not too good with JS.
I have a simple converter, when I enter in a textarea (onkeypress it fires a function). One problem is I don't want the whole HTML response, I want separe div as var.
I need the result and count. This is my script
function convert(){
var convertTxt = $("textarea[name='unit']").val();
$.post("convert.php",{convertVal: convertTxt}, function(data){
$("#output").html(data);
});}
With this I get the whole conver.php file but what I would like to get it inner html of two elements by Id. So for ex:
convert.php
echo "<div id='output'>$output</div>"
echo "<div id='count'>$count</div>"
The output I get after entering in a textarea
convert.php
<div id="output">this_has_been_converted</div>
<div id="count">3</div>
I would like to parse the date from inner this div's to my index.php. With the script above I get everything, div, id's but I want to get only the date inside the divs (separately). Because in index.php I want to place them in different places not one next to the other.
You can filter the data like this,
$.post("convert.php", {
convertVal: convertTxt
}, function(data) {
var output = $(data).filter("#output").text();
var count = $(data).filter("#count").text();
$("#output").html(output);
$("#count").html(count);
});
}
You'll need a method switch on your server-side file:
<?php
var methodRequested = $_POST['method'];
switch (methodRequested){
case "callFirstLine": sendFirstLine();
break;
case "callSecondLine": sendSecondLine();
break;
}
function sendFirstLine(){
echo "<div id='output'>$output</div>";
}
function sendSecondLine(){
echo "<div id='count'>$count</div>";
}
?>
Then your AJAX should say:
$.post("convert.php?method=callFirstLine",{convertVal: convertTxt}, function(data){
$("#output").html(data);
});}
Related
I am trying to get some data from the database. I create a function that is located in functions.php file that return a value. On another page, I create a variable and just get that value. I was trying to use the onkey to check the database but then I realize that i need to know the amount of tickets even if they don't type anything.
Here is the function:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$amount_of_tickets = $row['number_of_tickets'];
}
return $amount_of_tickets;
}
And, I am trying to check the database (without refreshing the page) and get the value on this page:
application.php
$amount_of_tickets = is_ticket_able($conn);
Then, I just check that $amount_of_tickets is not 0 or 1. Because if is one then some stuff have to change.
I am doing this (inside application.php):
if($amount_of_tickets !=0){
//show the form and let them apply for tickets.
//also
if($amount_of_tickets == 1){
//just let them apply for one ticket.
}
}
EDIT: I saw that AJAX would be the right one to use, but I am so confuse using it.
UPDATE:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
return $ticket;
}
application.php
$amount_of_tickets = is_ticket_able($conn);
<script type="text/javascript">
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
alert(global_isTicketAble);
if( global_isTicketAble == 0 ){
window.location.replace("http://www.google.com");
}
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
});
}
</script>
So, now the problem is that when I alert(global_isTicketAble); it doesn't alert the value from the database but it does alert everything that is inside application.php...Help plzzz
Server side
Assuming you need to check $amount_of_tickets periodically and this can be computed into application.php, inside that file you'll have
<?php
// $conn is defined and set somewhere
$amount_of_tickets = is_ticket_able($conn);
echo $amount_of_tickets;
exit(0);
?>
This way when the script is invoked with a simple GET request the value is returned in the response as simple text.
Client Side
ajax is the way to go if you want to update information on page without reloading it.
Below is just a simple example (using jQuery) that may be extended to fit your needs.
The code below is a JavaScript snippet. A global is used to store the value (globals should be avoided but it's just for the purpose of the example)
Then a function is invoked and the updated value is fetched from function.php script.
The function -prior termination- schedules itself (with setTimeout) to be re-invoked after a given amount of milliseconds (to repeat the fetch value process).
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
// eventually do something here
// with the value just fetched
// (ex. update the data displayed)
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
}
}
Note that $.ajax() sends the request but does not wait for the response (as async is set to true). When the request is received the function specified as success is executed.
Complete jQuery ajax function documentation can be found here
http://api.jquery.com/jquery.ajax/
I assume that you have a page (application.php) that displays a table somewhere.
And that you wish to fill that table with the data found in you database.
I'm not sure about WHEN you want these data to be refreshed.
On button click or periodically (like ervery 5 seconds)... But it doesn't matter for what I explain below.
In application.php:
Assemble all your page as you already know how.
But inside it, somewere, just insert an empty div where your table should show:
<div id="dynamicContent"></div>
Also add this script at the bottom of the page:
<script>
function getData(){
PostData="";
$.ajax({
type: "POST",
url: "function.php",
data: PostData,
cache: true,
success: function(html){
$(Destination).html(html);
}
});
}
getData(); // Trigger it on first page load !
</script>
There is 2 variables here... I named it "PostData" and "Destination".
About PostData:
You can pass data collected on the client side to your PHP function if needed.
Suppose you'd need to pass your user's first and last name, You'd define PostData like this:
Fname=$("#Fname").val(); // user inputs
Lname=$("#Lname").val();
PostData="Fname="+Fname+"&Lname="+Lname;
In your function.php, you will retreive it like this (like any normal POST data):
$Fname=$_POST['Fname'];
$Lname=$_POST['Lname'];
If you do not need to pass data from your client side script to you server side PHP... Just define it empty.
PostData="";
Then, about Destination:
This is the place for the empty "dynamic div" id ( I named it "dynamicContent" above).
Don't forget about the hashtag (#) for an id or the dot for a class.
This is a jQuery selector.
So here, PostData would be defined like this:
Destination="#dynamicContent";
The result of the ajax request will land into that "dynamic div".
This WILL be the result of what's defined in function.php..
So, if you follow me, you have to build your table in function.php...
I mean the part where you do your database query and your while fetch.
echo "<table>";
echo "<tr><th>column title 1</th><th>column title 2</th></tr>"
while ($row = sqlsrv_fetch_array($stmt)){
echo "<tr><td>" . $row['data1'] . "</td><td>" . $row['data2'] . "</td></tr>";
}
echo "</table>";
So if you have no data, the table will be empty.
You'll only get the table and table headers... But no row.
There is then no need for a function that checks if there is data or not.
Finally... About the trigger to refresh:
In application.php, you may place a button that fires getData()... Or you may define a setInterval.
It's up to you.
This is how I use ajax to refresh part of a page without reloading it completly.
Since ajax is new to you, I hope this answer will help.
;)
------------------------
EDIT based on Ariel's comment (2016-05-01)
Okay, I understand! Try this:
In application.php:
<div id="dynamicDiv"></div>
<script type="text/javascript">
// timer to trigger the function every seconds
var checkInterval = setInterval(function(){
checkTicket();
},1000);
function checkTicket(){
$.ajax({
type: "POST",
url: "function.php",
data: "",
cache: true,
success: function(html){
$("#dynamicDiv").html(html);
}
});
}
function noMoreTikets(){
clearInterval(checkInterval);
window.location.replace("http://www.google.com");
}
</script>
In function.php:
// Remove the "function is_ticket_able($conn){" function wrapper.
// Define $conn... Or include the file where it is defined.
// I assume that your query lookup works.
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
// Add this instead of a return.
if($ticket>0){
echo "There is still some tickets!"; // Text that will show in "dynamicDiv"
}else{
?>
<script>
$(document).ready(function(){
noMoreTikets();
});
</script>
<?php
}
Remember that your PHP scripts are executed server-side.
That is why your "return $ticket;" wasn't doing anything.
In this ajax way to call function.php, its script is executed alone, like a single page, without any relation with application.php, which was executed long ago.
It produces text (or javascript) to be served to the client.
If you want to pass a PHP variable to the client-side javascript, you have to echo it as javascript.
So here, if the PHP variable $ticket is more than zero, some text saying that there is still tickets available will show in "dynamicDiv" and the application page will not be refreshed. I suppose it shows a button or something that allows students to get a ticket.
Else, it will be the javascript trigger to "noMoreTikets()" that will land in the "dynamicDiv".
I have a problem with variables. I have a website using only Jquery which means that that I use #p1, #p02, ..., to navigate from one page to another.
I made an Ajax call which prints an id that I need in order to view my content. This id is printed in a div. The problem is that when I store the div in a variable like this:
$variable="<div class='something'></div>";
I can echo the variable but CAN'T use it in order to make queries. I know this is but programming but if I use sessions instead the identity didn't updated at all from page to page because of the using of #p01 instead of p1.php.
I also added the ajax.js file if this help you in order to advise me. The ajax.js file sends an identity to Ajax_page.php then I store this $_POST variable in a SESSION and then I echo this varible in Ajax_page.php. When i echo this variable it also printed in the div which is in the Show_content_page.php. I want the contents of that div. I want to use this div contents(identity) in order to make my php queries. Thats all.
Is there any way to make the $variable useful?
Here are the to sample files
Ajax_page.php
<?php
session_start();
if(!empty($_POST['show_an_anetoix']) ){
$_SESSION['anetoix_id']=$_POST['show_an_anetoix'];
}
echo $_SESSION['anetoix_id'];
?>
Show_content_page.php
<div id="p1" >
<?php
$variable="<div class='something'></div>";
echo $variable; //no problem
function_test($variable); //problem
?>
</div>
The ajax.js
/* Pass data with changePage */
$(document).on("pageinit", "#p1", function () {
$(document).on('click', '.anetoix_class', function(){
$.mobile.pageContainer.pagecontainer("change", "#p02", {
stuff: this.id,
transition: "flip"
});
});
});
/* retrieve data and run function to add elements */
$(document).on("pagebeforechange", function (e, data) {
if (data.toPage[0].id == "p02") {
var stuff = data.options.stuff;
var data = {"show_an_anetoix": stuff,};
$.ajax({
type: "POST",
url: "../show_an_anetoix.php",
data: data,
success: function(response)
{$(".show_an_anetoix").html(response);}
});
}
});
Not 100% sure what you mean. Are you asking, can you use a PHP variable in ajax? If so, I would do something like this:
<script>
$ajax_variable = "<?php echo $php_variable; ?>";
</script>
For several days, I cannot figure out how to design a solution for the following issue: I have a lot of items (around 1300) stored in database, each has its own "id", some "name" and a third property "enabled".
I would like to show on the same page to the user links to (all) the dialogs. Dialogs then shall show the "name" and allow the user to select OK/Cancel (i.e. enable/no action). (Changing of "enable" is made through a file some_file.php, which is already working properly and is not subject of this question.)
I have found similar questions like this or this but any of them so not need to pass variables between php and javascript like my dialogs.
I am not able to solve the problems stated below in comments:
javascript:
$(function(){
$('#dialog').dialog({
autoOpen: false,
width: 600,
modal: true,
buttons: {
'Cancel': function() {
$(this).dialog('close');
},
'OK': function() {
$.ajax({
url: 'some_file.php',
type: 'POST',
data: 'item_id=' + id,// here I need to pass variable, i.e. $line["id"] from the php loop
});
$(this).dialog('close');
}
}
});
$('.link_dialog').click(function(){
$('#dialog').dialog('open');
return false;
});
});`
html + php:
<?
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
// not sure here how to pass the "text" to some javascript function
if ($line["name"]=="") {
text = "Number ".$line["id"]." does not have any name.";
} else {
text = "The name of number ".$line["id"]." is ".$line["name"];
}
}
?>
<a href='#' class='link_dialog'>Dialog 1</a>
<a href='#' class='link_dialog'>Dialog 2</a>
<a href='#' class='link_dialog'>Dialog 3</a>
<div id='dialog' title='Name' style='display: none;'>
// not sure here how to extract the "text" from javascript function created above
</div>
jsfiddle demo (of course, not working)
If somebody sees the point, I would really appreciate your help. You can update my jsfiddle.
In PHP:
<?
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($line["name"]=="") {
$text[$line["id"]] = "Number ".$line["id"]." does not have any name.";
} else {
$text[$line["id"]] = "The name of number ".$line["id"]." is ".$line["name"];
}
}
/***
* Give each link unique ID (I've used 'dialog-n')
* Advantage to creating link dynamically:
* (what if the number of dialogs changes in the future?)
* Also suggest that you wrap these in a div
*/
$num_links = count($text);
for($i = 1; $i <= $num_links; $i++) {
echo "<a href='#' id='dialog-$i' class='link_dialog'>Dialog $i</a>";
}
HTML:
<div id='dialog' title='Name' style='display: none;'>
</div>
In Javascript:
var DIALOG_TEXT = <?php echo json_encode($text); ?>; //Pass text via JSON
$('.link_dialog').click(function() {
var link = this;
//Get link ID
var link_id = link.attr('id').split('-'); //Split string into array separated by the dash
link_id = link_id[2]; //Second array element should be the ID number
var msg_text = DIALOG_TEXT[link_id]; //Retrieve associated text
//Insert text into dialog div
$('#dialog').text(msg_text); //Use .html() if you need to insert html
$('#dialog').dialog({
buttons: {
"Cancel": function() {
$(this).dialog('close');
},
"OK": function() {
$.ajax({
url: 'some_file.php',
type: 'POST',
data: 'item_id=' + link_id, //Use link id number extracted above
});
$(this).dialog('close');
}
}
});
return false;
});
I have not tested the above, you will probably have to modify for your needs.
OPTION 2:
If you intend to have the dialog content generated dynamically (e.g. only when the user clicks the link), you can do the below
jQuery('#dialog').load('content_generator.php?item_id=**[your id]**').dialog('open');
where 'content_generator.php' takes the given id and outputs the appropriate text, which ".load()" inserts into the dialog.
Option 2 is based on the answer given by Sam here
What you are trying to do is called dynamic content loading. My last example does this by inserting the necessary data (as JSON) and generating the content directly on the page.
This next method may not be suitable for what you are trying to do, but may be useful later.
Instead of retrieving the data and generating the content on the page itself, we use an external page to provide content for us. This reduces server load by only providing the needed content, and can increase user interactivity (because the page doesn't have to load up all the information before it gets displayed to the user). See [here][1] for further information about AJAX.
Advantages: Separating the content generation from the page a user accesses. What if you need to show the same/similar content elsewhere on the website? This method allows you to reuse the code for multiple use cases.
You can even combine this with the previous method. Just use a separate PHP file to generate your dialog content and links en masse (rather than per click as shown below), which gets called and loaded in on $(document).ready()
Per click example:
Generate the content per click
A separate PHP file - dialog_text_generator.php:
<?
//DON'T ACTUALLY DO THIS. ALWAYS SANITIZE DATA AND AVOID USING mysql_ prefixed
//functions (use mysqli or PDO).
//This is just to illustrate getting data from the DB
$item_id = $_REQUEST['item_id'];
$query = "SELECT * FROM `stuff` WHERE item_id = $item_id";
$query_results = mysql_query($query, $db_connection);
$num_matches = count($query_results);
$text = array();
for($i = 0; $i < $num_matches; $i++) {
$current_item = $query_results[$i];
//Print out content
//replace 'name' with whatever field your DB table uses to store the item name
if($current_item['name'] == '') {
echo "<p>Number $item_id does not have any name.</p>";
} else {
echo "<p>The name of number ".$item_id." is ".$current_item['name']."</p>";
}
}
?>
Javascript in your main page:
<script>
$('.link_dialog').click(function() {
//On user clicking the link
var link = this;
//Get link ID
var link_id = link.attr('id').split('-'); //Split string into array separated by the dash
link_id = link_id[2]; //Second array element should be the ID number
//autoOpen set to false so this doesn't open yet, we're just defining the buttons here
$('#dialog').dialog({
autoOpen: false,
buttons: {
"Cancel": function() {
$(this).dialog('close');
},
"OK": function() {
$.ajax({
url: 'some_file.php',
type: 'POST',
data: 'item_id=' + link_id, //Use link id number extracted above
});
$(this).dialog('close');
}
}
});
//Load content from PHP file into dialog div and open the dialog
//Obviously use the actual path to dialog_text_generator.php
jQuery('#dialog').load('dialog_text_generator.php?item_id='+link_id).dialog('open');
return false;
});
</script>
Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>
I have the following html:
<h4>Add Steps</h4>
<ul id="pasi">
<li>
<span>Pasul 1: </span><textarea id="pas"></textarea>
<input id="add_pas" type="button" value="Add Step" onclick="add_pas()"/>
</li>
<input id="" type="button" value="Add recipe" />
and this jquery function:
function add_pas() {
var pas = "Pasul " + i;
var list = $('#pasi');
var html = "<li class='pas-"+ pas +"'><span>" + pas + "</span><textarea></textarea><img src='../images/x.png' /></li>";
list.each(function(){
$(this).append(html);
});
i++
}
The function adds a new step when the button is clicked.
SQL:
TABLE recipe_steps (id, recipe_id,sort_oder,description)
My question is how do I insert the custom number of steps into the database, and then how to retrieve it.
A first thaught was to insert all the steps into a vector(steps[]) but I don't really know where to start.
Please take in consideration that I'm a begginer in php, mysql, jquery .
Thank you and I hope I made it as clear as possible.
I don't understand how you're transitioning from js to inserting into SQL (but I may just be missing something!), but IMO you should use a jquery $.post function to call a separate .php file to do the insertion
$("#FORM_SUBMIT_ID").click(function() {
$("#ENTIRE_FORM_NAME").submit( function () {
$.post(
'SQL_INSERTION.PHP', //NOTE <-- assumes .php file is in same dir as curr file
$(this).serialize(), //This takes your form and auto separates it
function(data){
$("#ERRORS").html(data); //This will append error text to a div if you wish
}
);
return false;
});
});
Then, on your .php file you will have an array in $_POST with ALL the form values that were filled out. To test how serialize() formats your form into an array, on your php file just write
<?php print_r($_POST); ?>
I believe that should be enough. Then from there, for custom insertion, depending on how many values you have that can vary in presence, simple if/else if statements may be good enough.
i.e. if ($_POST['name']){ //code}
Alternatively, you can pass in a form "type" along with the serialized data to .php, and that will go into the $_POST array.
I came up with this that worked
function trimite(){
var pasi = {}; //initializing an array
var k=0;
$(".nimic").each(function () { //class of the <textarea>
pasi[k]=$(this).val(); //takes the value for each of the textareas created
k++;
});
$.ajax({ // sends all the textarea created to the php processing script
type:'POST',
url:"functions/add_recipe.php",
dataType:"json",
data:{
'pasi':pasi
},
success: function(data){
},
error: function(){
alert('error');
}
});
return false;
}