Modifying AJAX from insert to update if modal is clicked again - javascript

I've built a CMS that uses bootstrap Modals within div areas so that when the user clicks on the div where they want to insert content, a modal comes up with a tinyMCE text editor area where they can put images or text. Once they have, they hit the save button in the modal which closes the modal and shows the preview of what they just did.
Also, when they hit the save button, I perform an AJAX request that calls an addPanel.php script in order to insert a record for that panel, panel type and content.
THis works perfectly except for the fact that if they click on the modal again and do this all over to edit their content, it just saves another panel.
I need to slightly modify what I"m doing now to either:
Get the ID of the panel that was created on the last ajax request and now perform a mysql update on the record for the content (as the panel ID and panel type will remain the same)
Keep the current process but set the last panel's 'active' column in mysql to '0' (not as big a fan of this approach but will accept it).
Basically, what I have works but if the user clicks on the modal anymore after the first time, I would be updating instead of inserting.
Here is the mysql being performed in addPanel.php:
$content = $_POST['page_content'];
$addContent = "
INSERT INTO content(content)
VALUES('$content');
";
if ($mysqlConn->query($addContent) === TRUE) {
$cont_id = $mysqlConn->insert_id;
$data['last_insert_id'] = $cont_id;
echo json_encode($data);
} else {
echo "Error: " . $addContent . "<br>" . $mysqlConn->error;
}
$panelID = $_POST['panel_type'];
$pageID = $_POST['page_id'];
$addPanel = "
INSERT INTO panels(panel_type_id, page_id, cont_id)
VALUES ('$panelID', '$pageID', '$cont_id');
";
if ($mysqlConn->query($addPanel) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $addPanel . "<br>" . $mysqlConn->error;
}
And the script/AJAX to show an example of what I'm doing currently for a panel:
<script type="text/javascript">
$("#leftHalfForm").submit(function(e){
var leftContentVar = tinymce.get("leftHalfTextArea").getContent();
$(".leftContent").html(leftContentVar);
$("#leftHalfPageContent").val(leftContentVar);
// jQuery.noConflict();
var string = $('#leftHalfForm').serialize() + '&page_id=' + page_id;
console.log(string);
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "addPanel.php",
data: string,
cache: false,
success: function(response){
console.log(JSON.stringify(response));
console.log(string);
$('#leftFiftyModal').modal('hide');
$('.modal-backdrop').remove();
}
});
return false;
});

Related

Ajax POST working, but php document cannot get data variable

When I post something, the network tab of chrome shows that the post is going through with the correct variables, but on the php end, the POST global is empty, and the method on the page is GET for some reason. I hope I am not just missing something obvious, I spent like 4-5 hours troubleshooting. What is occuring, or is suppose to, is that when you type anything in the searchbox, an event listener in the js file triggers and POSTs the value of the search box to the php of the storepage.php. The search bar itself is actually on a seperate php file which makes a header for every html page, but the php that queries the database is in the storepage.php
Picture of network results from entering items into search (notice variable searchInput at bottom of image)
This is where the Ajax POST happens: searchItUp.js
$(document).ready(function() {
console.log("Document Ready. Listening for search bar key presses...");
$('.SearchBar').keyup(function() {
console.log("Key pressed.");
var searchBoxValue = document.getElementById('superSearcher').value;
console.log("Current searchbox value: " + searchBoxValue);
jQuery.ajax({
method: "post",
url: "storepage.php",
data: {searchInput: searchBoxValue},
datatype: "text",
success: function () {
console.log("Ajax functioning properly...");
$('.content').load(document.URL + ' .content>*');
},
error: function() {
console.log("Ajax NOT functioning properly...");
}
});
});
});
Next is the section of the php document (storepage.php) where the javascript file is included, and the POST is directed to.
if (isset($_POST["searchInput"]) && !empty($_POST["searchInput"])) {
echo "searchInput is set... ";
} else {
echo "searchInput is not set... ";
}
echo $_SERVER['REQUEST_METHOD'];
$searchInput = $_POST['searchInput'];
if ($searchInput=="") {
// query all game information based on text in the search bar
$query = "SELECT ProductID,ImgID,Image,GameName,ESRB_ID,ESRB_Img,Rating,ReleaseDate,Description,Tags,Price,PlatformID,PlatformName
FROM PRODUCTS
JOIN PRODUCT_IMAGES USING (ImgID)
JOIN GAME_INFO USING (GameID)
JOIN PLATFORMS USING (PlatformID)
JOIN ESRB USING (ESRB_ID)";
$statement = $db->prepare($query);
$statement->execute();
$GameList = $statement->fetchAll();
$statement->closeCursor();
echo "<script>console.log( 'Game database queried WITHOUT search' );</script>";
}
else {
// query all game information if search is empty
$query = "SELECT ProductID,ImgID,Image,GameName,ESRB_ID,ESRB_Img,Rating,ReleaseDate,Description,Tags,Price,PlatformID,PlatformName
FROM PRODUCTS
JOIN PRODUCT_IMAGES USING (ImgID)
JOIN GAME_INFO USING (GameID)
JOIN PLATFORMS USING (PlatformID)
JOIN ESRB USING (ESRB_ID)
WHERE GameName LIKE '%$searchInput%'";
$statement = $db->prepare($query);
$statement->execute();
$GameList = $statement->fetchAll();
$statement->closeCursor();
echo "<script>console.log( 'Game database queried WITH search' );</script>";
}
I have tried everything I could find online, and I have probably looked at all relevant stackoverflow, and other, posts, but I can't figure it out for the life of me.
You're invoking the script twice. First with $.ajax, where you're sending the search parameter.
Then in the success: function, you invoke it again using $('.content').load. This sends a GET request without the search parameter. So it doesn't show the result of the search in .content.
The AJAX request should return whatever you want to show. Then you can do:
success: function(response) {
$(".content").html(response);
}
Another option is to pass the parameter when calling .load. That changes it to a POST request:
$(document).ready(function() {
console.log("Document Ready. Listening for search bar key presses...");
$('.SearchBar').keyup(function() {
console.log("Key pressed.");
var searchBoxValue = document.getElementById('superSearcher').value;
console.log("Current searchbox value: " + searchBoxValue);
$('.content').load(document.URL + ' .content>*', {
searchInput: searchBoxValue
});
});
});

display ajax result on new page

I would like to display the results of an ajax request on a new page rather than the page the ajax call was made from. Essentially I have a membership directory page. When the user clicks on the member ID cell on that page, an ajax call sends the ID to the server and completes an HTML table to display that member profile. If I add a <div> element below the membership directory page, I can make the profile information table display below the membership directory table. But I want the profile table to display on different page.
JavaScript:
$jq.ajax({
url : ajax_mmmp.ajax_url,
type : 'post',
data : {
action: 'mmmp_profile_member_id_callback',
mem_id : member_id
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
// Return response to client side
alert("Submit Success");
$jq('#display_profile').html( data );
return false;
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
But when I create a new page with the same <div> element and try to open that page prior to the ajax call, the result does not display.
var mem_profile = "http://localhost:81/wordpress/view-member-profile"
window.open (mem_profile,'_self',false)
$jq.ajax({
url : ajax_mmmp.ajax_url,
type : 'post',
data : {
action: 'mmmp_profile_member_id_callback',
mem_id : member_id
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
// Return response to client side
alert("Submit Success");
$jq('#display_profile').html( data );
return false;
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
Putting aside the question of whether it is a good idea to take that approach, the answer to your question is yes. You can open a new window and write the resulting HTML to it:
// open a new window with no url and a title. check the docs for other args to open()
let win = window.open('','My New Window');
// write some HTML to that window
win.document.write('<table><tr><th>test</th></tr></table>');
After some further research, I'm almost there. I do not presently have a "form" to submit. The user simply clicks on a table cell which contains a member ID number. I want to 'submit' that value as input on another page which displays the membership profile. I have been successful in temporarily adding a HTML form that works as desired if I type the member ID in an input field. So I decided what was needed was to create a hidden form in JS that used the ID value that was clicked on. It appears that I can not insert revised code into a comment, so I opted to 'Answer' my original question with updated code.
Working HTML Form included on Membership Directory Page:
$site_url = site_url();
$location = $site_url . "/view-member-profile";
?>
<form action="<?php echo $location;?>" method="post">
<input type="text" class="input_member_id" id="input_member_id" name="Member_ID">
<input type="submit" id="submit_member_id" name="submit_member_id" value="Submit">
</form>
My attempt to create a similar hidden form in JS:
var $jq = jQuery.noConflict();
$jq(document).ready(function(){
// Add listener for Member ID click in member directory
$jq("#mem_dir").delegate(".member_id", "click", function() {
var mem_id = $jq(this).text();
var mem_id = mem_id.trim();
alert ("ID is: " + mem_id);
var site_url = document.location.origin + '/wordpress';
var form_location = site_url + '/view-member-profile';
alert ("Submit to location is: " + form_location);
var form = $jq('<form method="post" class="js:hidden">').attr('action', form_location);
//var input = $jq('<input type="hidden"'>).attr('value', mem_id );
//form.append(input);
//$jq('body').append(form);
form.submit();
}); // End of Click Member ID Listener
}); // End of Main Document Ready Function
The problem I am having with the JS file is with inserting the mem_id value into the input form. The JS file correctly opens the new View Member Profile page. (Note the 3 // lines just prior to the form.submit). When uncommented, the Profile page opens, but table values are empty (i.e. mem_id value was not passed to the page).
Thanks for any advice. If I was supposed to list this as a new question, please let me know.

how to fetch data from sql server database in php without refreshing the page

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".

data-attribute wont submit content

I'm busy developing my first Twitter application. However, I'm stuck at something basic which I cant solve for some reason. I used to use data-attributes alot, but I just cant get it to work. It just wont submit the content of my data-attribute
Part of my HTML.
<div id="invTweet" class="_invitation-tweet-inner no-select" data-tweet="Here comes the content of the tweet which will be submitted">Here comes the content of the tweet</div>
<div id="post-invitation-tweet" class="button blue post-tweet">Post Tweet</div>
Part of my Javascript
var tweet = $("#invTweet").attr("data-tweet");
$(document).on('click',"#post-invitation-tweet",function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "../includes/db-requests/db-postInvitationTweet.php",
data: {tweet:tweet},
success: function(data){ finishInvitationTweet(data); }
});
});
function finishInvitationTweet(data) {
alert(data);
}
I use alert(data) for debugging purposes. When I click on the Post Tweet button, an alert will open with the echo "Undefined index: tweet emptyTweet". Look below for a snippet of my db-postInvitationTweet.php:
//Get Tweet data
$tweetMsg = safe($mysqli,$_POST['tweet']);
//Check if $tweetMsg is empty. No > post tweet.
if ($tweetMsg != '') {
$post_tweet = $connection->post('statuses/update', array('status' => $tweetMsg));
if (187 == $connection->http_code) {
echo "statusDuplicate";
die();
}
if (!$post_tweet) {
echo "tweetError";
} else {
//Update the invitation_sent column in database
$stmt = $mysqli->prepare("UPDATE members SET invitation_tweet = '1' WHERE oauth = ? ") or die (mysqli_error($mysqli));
$stmt->bind_param('s', $access_token['oauth_token']);
$stmt->execute();
$stmt->close();
echo "tweetSuccess";
}
} else {
echo "emptyTweet";
}
What am I missing :')
What version of jQuery are you using? As of around version 1.4 the appropriate way to access a data attribute would be through the data() method, see method signature and docs here.
If you change that you may be able to get it to work just fine. See jsFiddle with working solution as proof of concept.
Changed
var tweet = $("#invTweet").attr("data-tweet");
To
var tweet = $("#invTweet").data("tweet");

Load dialog contents and pass variables

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>

Categories

Resources