Load dialog contents and pass variables - javascript

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>

Related

Modifying AJAX from insert to update if modal is clicked again

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;
});

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

Javascript post data

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);
});}

Can't place jQuery inside loaded document.ready: not called

I have a page called: contact_profile.php that uses jquery .load to load info into a div.
$('#json_comments').load('json_comments_content.php');
json_comments_content.php looks like this:
<?php
require_once 'core/init.php';
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('login.php');
}
$contact = new Contact();
//check to make sure there is current contact selected, otherwise redirect to index. This helps when you deselect a contact from menu bar while on contact page.
if (!($contact->isSelected())) {
Redirect::to('index.php');
}
?>
<div class="items general-item-list">
<div class="item">
<div class="item-head">
<div class="item-details">
<img class="item-pic" data-field="pic_url" src="">
<span class="item-label" data-field="datetime" data-value="" data-pk=""></span>
</div>
</div>
<div class="item-body"></div>
</div>
</div>
Load More...
<script type="text/javascript">
$(document).ready(function() {
$('.comments_data').loadmore({
source: 'json_comments.php',
step: 15,
userid: '<?php echo $user->data()->id; ?>'
});
//on load, disabled the comments editable info on page load so it looks better.
$('#json_comments a').attr("data-disabled", "true");
$.fn.editable.defaults.mode = 'inline';
});
</script>
I am using a custom plugin called 'loadmore' that will load more data on my page from a mysql database. It works fine.
However, I have to use the following code for the data that is supplied by the loadmore plugin:
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
That code is using the X-Editable plugin for jQuery: http://vitalets.github.io/x-editable/
If I place the code in the loaded content's page inside the document.ready function, it never gets called!
Here's what my loadmore plugin looks like. If the code for X-Editable is placed there it will work properly. It would be better to have the code placed in the loaded page and NOT in the plugin - that way the plugin can stay generic.
Hope I was clear on my problem.
Here's the loadmore custom plugin:
(function ($) {
"use strict";
$.fn.loadmore = function(options) {
var self = this,
settings = $.extend({
source: '',
step: 2,
userid: '',
}, options),
stepped = 1,
item = self.find('.item'),
items = self.find('.items'),
finished = function() {
// hide the load more button
self.find('.items-load').remove();
},
append = function(value) {
var name, part, id, userid, canedit;
item.remove();
for(name in value) {
if(value.hasOwnProperty(name)) {
id = value['id'];
userid = value['user_id'];
part = item.find('*[data-field="' + name +'"]');
//find anything that has a can edit class and then add the general editable class for x-editable to work.
canedit = item.find(".can_possibly_edit");
if(part.length){
part.text(value[name]);
//add the value to an image if there is one for x-editable to work.
if($(part).is("img")) {
$(part).attr("src", value[name]);
}
//only make the current user's stuff editable
if(settings.userid == userid ) {
//add edit_me to the classes so x=editable can work. but then remove edit_me and the editable class so x-editable doesn't work for data that doesn't belong to the user(found in the else clause below).
$(canedit).addClass('edit_me editable editable-pre-wrapped editable-click editable-disabled');
$(canedit).attr('data-value', value[name]);
//there must be an id field in the json so it can be assigned to the primary key for x-editable to work.
$(canedit).attr('data-pk', id);
} else {
//remove hyperlink stuff and just leave the text to view only.
$(canedit).removeClass('edit_me editable');
}
}
}
}
item.clone().appendTo(items);
//this works if it's placed here only!
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
},
load = function(start, count) {
$.ajax({
url: settings.source,
type: 'get',
dataType: 'json',
data: {start: start, count: count},
success: function(data) {
var items = data.items;
if(items.length) {
$(items).each(function(index, value) {
append(value);
});
stepped = stepped + count;
}
if(data.last === true) {
finished();
}
}
});
};
if(settings.source.length) {
self.find('.items-load').on('click', function(){
load(stepped, settings.step);
return false;
});
load(1, settings.step);
} else {
console.log('Source required for loadmore.');
}
};
}(jQuery))
It's almost like on the loaded page: json_comments_content.php I need to run the loadmore plugin on document.ready and THEN once the loadmore has been completed, return back to the page and run:
$('.edit_me').editable({
emptytext: ".....",
url: "ajax_xeditable_update.php?table=comments",
});
Not sure if it matters, but the loadmore script is included on my main page from: 'js/loadmore.js'. It's in a subdirectory.

Ajax POST is not posting onclick to current page

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>

Categories

Resources