I've created a bookmark page that retrieves links from a database and displays it. I'm able to log in, add new links & delete them. However, when I delete an entry it displays delete.php instead of loading the page onto itself (the query does work).
I've most likely over-complicated my code at this point and am probably overlooking something simple, as I've used a lot of JavaScript for other elements of the page.
The entries are added dynamically so this part of the HTML is being appended:
<h2>
[x]
</h2>
<a href="'+url+'" target="iFrame" class="linkURL">
<div class="bookmark">
<h3 style="float: left;">'+title+'</h3>
<br />
<p>'+desc+'</p>
</div>
</a>
JavaScript:
// DELETE FUNCTION
$("h2 a").click(function() {
return false;
var action = $(this).attr('href');
var form_data = {
URL: $("#linkURL").attr('href'),
is_ajax: 1
}; // form_data
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success') {
alert('Successful delete!');
} else { // if
alert('Delete failed.');
} // else
} // function(response)
}); // ajax
return false;
}); // h2
The page is located here: http://samaradionne.com/links6/ if it is easier to view the whole thing.
You are using both an anchor tag a and a click event. You are getting the actual delete.php page because when you click on the anchor tag it works just like any regular link. You have no where in your code something that says "hey, don't actually follow this link like normal".
To not follow the link, you need
[x]
Furthermore, you attached your jQuery click event to the h2, which is not bad in of itself, just confusing as the intent is to actually click the link. In that case, you need:
$("h2 a").click(function(){});
Lastly, to bring this all together, you could do the following:
$("h2 a").click(function(){
// your normal logic
return false; // don't follow link
});
And then you don't have to have the onclick inside the anchor tag.
Since my links were dynamically generated, my .h2 a click was attaching itself to something that wasn't there yet. I added an event trigger to my append function that calls to my delete function.
Problem solved.
Related
how is it possible to achieve this:
http://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
using php?
let's say that I have the following a url:
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager?article=my-article
to get there I have a link in pages-folder/works.php :
link
which should open content-manager.php in which inside a div I should load my-article.php
EDITED:
I have an index file in which a load into the div.container all the pages I need, so in this case my works.php file is loaded int the div.container using using:
<?php
$page = $_GET['page'];
if(!empty($page)){
$page .= '.php';
include($page);
}
else {
include('pages/home.php');
}
since I also needed to update the url without reloading the page I use this script:
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
}
}
$('ul.menu li a').on('click', function(){
var page = $(this).attr('href');
var pageUrl = page.split("/");
pageUrl = pageUrl[1];
$('.container').load(page + '.php', function(){
//fadeout old content
//fadein new content
});
ChangeUrl('Page1', '?page=' + page);
return false;
})
once I have my works.php loaded into the div.container I have the above mentioned link which should lead me to: pages-folder/works-folder/content-manager.php
it is in this page where I'd like to load my-article.php inside the main div of content-manager.php
I thought that adding the ?article= variable would have worked using the same system as above:
$article = $_GET['article'];
if(!empty($article)){
$article .= '.php';
include($article);
}
else {
...
}
but it doesn't...
how can I achieve this?
Why you don't just add you article as a query param ?
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager&article=my-article
and make a link like this
link
This is just an exemple to understand what you want to do, don't use this kind of code in production, he is vulnerably to CSRF attack
EDIT: with echo it's better sorry
I haven't answered your question per se but this is the sort of code you are looking for:
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
Explanation
How does $_GET work?
$_GET is a super global variable - meaning it can be accessed from anywhere.
It is a an associative array of variables passed to the current script via the URL parameters.
These are specified following a question mark (?) in the URL. To specify multiple parameters you must use the ampersand (&) character between each one.
$_GET must be specified at the end of the URL after everything else.
http://www.example.com/thisPage.php?page=a
http://www.example.com/thisPage.php?page=a&theme=light
The first URL will produce a $_GET with one element which can be accessed as: $_GET["page"] and would return a string of one character a.
The second will produce:
$_GET["page"]; // returns "a"
$_GET["theme"]; // returns "light"
Notice that for each parameter a new key-value pair is created.
I wrote a comprehensive explanation of superglobals on SO Documentation, but that has since been deprecated. RIP my hard work :P
Showing differing content
As you can see from my answer above. You can use simple if statements to check what the value is.
Firstly, ensure that $_GET isset and then check the value.
I have converted the value of the array to lowercase since "A" is not the same as "a".
The example you linked to really over-complicates things. There is honestly no need for all that regular expressions, and it also relies on JavaScript which is not necessarily a good idea.
With my example at the top, there is no difference between user experience as PHP is server sided thus all the content is worked out and then served to the user.
One step further
Using this you can go that extra step and have an event listener and combine it with AJAX.
Altering my initial example you can have the following.
I have used the jQuery library as it is a lot easier to implement.
<div id="test">
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
</div>
function myAJAX() {
$("a").on("click", function(e) {
e.preventDefault();
// get the clicked page number
if (this.href.indexOf("&") > -1) {
var d = this.href.substring(this.href.indexOf("page=") + "page=".length, this.href.indexOf("&"))
} else {
var d = this.href.substr(this.href.indexOf("page=") + "page=".length)
}
$.ajax({
method: "GET",
url: "t.php",
data: "page=" + d,
success: function(data, textStatus, jqXHR) {
// change the content of the #test div
$("#test").html($($.parseHTML(data)).filter("#test")[0]);
myAJAX();
}
});
});
}
myAJAX();
Notice that the HTML is not being wrapped in <div id="test"> which is so that the JavaScript can find that element and change it in the function.
$("#test").html($($.parseHTML(data)).filter("#test")[0]); is the line that is fetching the HTML and changing it with the data from the page you tried to click on.
I also call the function inside itself so that it will reattach on the anchor links. If you remove this line then the page will redirect as normal.
The good thing about this implementation is that if your user does not have JavaScript then the page will act as normal and there will be a normal reload of the site.
No need for any extra work on your part.
Good day folks. I need to figure out how to perform an action using Ajax once I have linked to a specific section on a page. I already know how to get to the designated DOM element on the other page, but I would like to go further as to perform some action using ajax once it has taken the visitor to that point.
eg.
<nav>
<ul><li></li></ul>
</nav>
Will take me to this about.php page to the "team" div
<div>
<div><a name="team"></a></div>
</div>
But then I would like to run some Ajax automatically that would usually be executed when the user clicks on some object in the "team" div. So should the user get to this section by way of the link up above, it will take them straight to the content. Does that make sense?
I'm going to go out on a limb and assume you're using jQuery's animate() for the scrolling:
$('html, body').animate(
{ scrollTop: $("#something").offset().top },
1000,
function() {
someAjaxFunction();
}
);
var someAjaxFunction = function() {
$.ajax({
url: '/something/'
}).done(function(data) {
// Done!
});
};
We're using the callback function argument given to animate() to fire off our ajax request.
You can use jQuery's scrollTo() to scroll to the area on the page, then use the complete function to call you ajax after the scroll has finished.
Detailed Description here
$('body').scrollTo('#target', function()
{
// Do your AJAX Thaaang
});
This check can be run to determine if the user has navigated directly to the teamDiv. Running it on page load would allow you to catch it in the event that the user was deep linked to the teamDiv from another page:
if (/#team/.test(window.location.href)) { // perform Ajax query here... }
Note: In the example link, you use the id team whereas the div's ID attribute is set to teamDiv. They need to be the same for this to work.
So the code would run if the user clicks some object in the "team" div?
In that case, is this an option?
<div>
<div id="teamDiv"><a name="team"></a>some element</div>
</div>
<script type="text/javascript">
$(function() {
$("#teamDiv").click(function() {
//put what you want to happen when the user clicks something in
//teamDiv here
});
})
</script>
My suggestion would be to read the current loaded url:
$(document).ready(function () {
var location = window.location.href;
if(location.indexOf('#team' > -1) {
// do something
}
}
You can check location.hash (http://www.w3schools.com/jsref/prop_loc_hash.asp) to determine if hash existed.
If you want to do something in each variants of navigation to this div: click and scroll you can use something like this:
$(document).bind('scroll', function() {
if($(this).scrollTop() > $('.your-div').top()) {
alert('do something');
}
})
This problem drive me nuts for two days.
I have strongly typed view with text area. User can write comment in that area. After button click I save comment and return view from action method with comment id and comment text. Returned view I add to div called "messages" and it works. Comments saved, View returned, Display fine but when I right click in browser for page source div "Messages" is empty.
This thing makes me problem. Each comment has edit button and if there is 5 comments in messages div when I click edit I got edit function called 5 times. But when I hard code HTML with comments in div messages it works. But when I ajaxify page nothing works as it should.
Here is the code:
<script>
$(function () {
$('#addMessageForm').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#messages').prepend($(result).fadeIn('slow'));
}
});
return false;
});
});
</script>
#using (Html.BeginForm("AddMessage", "Comment", FormMethod.Post, new { id = "addMessageForm" }))
{
#Html.TextAreaFor(a => a.CommentText);
<input type="submit" value="Submit Comment" />
}
<div id="messages">
</div>
This is add comment Action Method:
[HttpPost]
public ActionResult AddMessage(CommentModel model)
{
model.Author = "Vlada Vucetic";
Random r = new Random();
int n = r.Next(1, 1000000);
model.CommentId = n;
return View("CommentView", model);
}
This is what happen when I click edit button. But as I said when I add hard code comment div in div messages and click edit it called only once. I have no idea what is happen here? Why page source doesn't display anything in browser...
This is comment view. This is what I add to div messages.
#model Demo_AjaxPosting.Models.CommentModel
#{
Layout = null;
}
<script src="../../json2.js" type="text/javascript"></script>
<script>
$('.editButton').live('click', function (e) {
e.preventDefault();
var container = $(this).closest('div'); //$(this).closest('.commentWrap');
var itemId = container.attr('id');
alert(itemId);
var nestId = '#' + itemId;
var txt = $(nestId + ' #commentTextValue').text();
$(nestId + ' #commentTextValue').remove();
$(nestId + ' #editButton').remove();
$(nestId).prepend('<textarea id="editArea">' + txt + '</textarea>');
$(nestId).append('<input type="submit" value="Ok" class="btnOk" />');
})
</script>
<div style="border: 1px solid #dddddd;">
#Html.ActionLink(#Model.Author, "SomeAction") #Model.CommentId
<div class="commentWrap" id="#Model.CommentId">
<p id="commentTextValue">#Model.CommentText</p>
<a class="editButton" href="#">Edit</a>
</div>
</div>
The page source shows the page as it is initially received from the server. The DOM is created from the source and displayed. If you later add comments to the DOM (using jQuery), it will be displayed but the page source isn't updated. So far, that's expected behavior.
If you want to inspect the HTML after comments have been added, use a tool like Firebug. It works on the DOM and nicely handles dynamic parts.
The reason your event handler is executed several times is that you add it several times. Every time a comment is added, the Ajax answer transmits (and the browser executes) a script with the following line:
$('.editButton').live('click', function (e) {
As a result, you end up having several event handlers installed. They might have identical code. But that doesn't matter. They are installed several times. So if you click the "Edit" link, several of them are executed and you get several text boxes.
The solution is to move the Javascript code (including the SCRIPT tags) out of the CommentView and into the view of the main page.
Im building a small application and I have some click events binded to some span tags that trigger AJAX requests to a PHP file which queries a MySQL database and spits out the results to populate the targeted area.
However, sometimes i will be clicking the buttons and I have conditionals in place to stop multiple clicking to prevent duplicate content being added numerous times.
I click on a button and firebug tells me that the ajax request had actioned more than once, sometimes it will multiply - so it will start by doing it 2 times or another time it will carry our the request 8 times on one click and obviously flood my content area with duplicate data.
Any ideas?
EDIT
Code for a button is as follows:
<span class="btn"><b>Material</b></span>
This would be enabled by
$('.btn').bind('click', matOption);
and this would be controlled by something like this
var matOption = function() {
$(this).addClass('active');
// remove colours if change of mind on materials
if($('#selectedColour').val() >= 1) {
$('.colour').slideUp(500).children().remove();
$('#selectedColour').val('');
$('.matColOpt .btn').html('<b>Material Colour</b>').removeClass('active').css('opacity', 0.55);
$('.btn').eq(2).unbind('click', colOption); // add click to colour
$('#stage h1 span').eq(2).fadeOut(500);
$('.paperOpt .btn').css('opacity', 0.55).unbind('click', selectPaper);
}
// ajax req for available materials
var cid = $('#selectedColour').val();
var target = $('#notebookOpts .matOpt ul');
$.ajax({
type: "GET",
url: ajaxFile+"?method=getMaterials",
beforeSend: function() {if($('.mats').children('li').size() >= 1) { return false; }},
success: function(data) {
target.append(data).slideDown(500);
$('.mats li').bind('click', matSelect);
},
error: function() {alert('An unexpected error has occurred! Please try again.');}
});
};
You're probably binding your matOption function more than once.
if(!window.matOptionBound){
$('.btn').bind('click', matOption);
window.matOptionBound = true;
}
If you have a code that binds an event handler to a DOM element repeatedly then that event handler does gets executed repeatedly on the event. so if your code such
$("span").click(myHandlerFunction)
gets executed thrice, then you have just told jQuery to fire myHandlerFunction thrice on every click of span. It would be good to make sure there is no such condition goign on in your code. If that is not true then please post your code so that I can help further.
PS: The safest way to do this will be as
$("span").unbind("click",myHandlerFunction).bind("click",myHandlerFunction)
I'm a newbie to jquery, but am trying to use it in my project.
I'm trying to loop through all the links inside #rate_box and add a click event to them. This click event will post some data to an external php script, and then it should unbind the click events on all of the links (so people cannot rate twice in quick succession.) Then it should put the data recieved from the php script into a span tag called #status.
However my code isn't even executing the alert("Index: "+i). Am I binding it correctly?
<script type="text/javascript">
$(document).ready(function(){
$('#rate_box a').each(function(i) {
$(this).click(function() {
alert("Index: "+i);
$.post("../includes/process/rating.php", {id: "<?php $game_id ?>", type: "game", rating: i+1},
function(data) {
$('#rate_box a').each(function(i) {
$(this).unbind('click');
}
$('#status').html(data).fadeIn("normal");
});
});
});
});
</script>
You don't need to loop through each link binding a handler individually, you can just do this:
// bind click handler to all <a> tags inside #rate_box
$('#rate_box a').click(function() {
});
Same goes for unbinding:
$('#rate_box a').unbind('click');
As far as your code, it probably isn't executing because you have not closed the inner each when you are unbinding the element tags, so it is invalid javascript:
$('#rate_box a').each(function(i) {
$(this).unbind('click');
} // <- missing closing ");"
You should really use a tool like Firebug or Firebug Lite to debug your javascript, although something like the above should just give you a Javascript error in most browsers.
EDIT If you want to find the index of the current link when it is clicked upon, you do this:
var links = $('#rate_box a');
$(links).click(function() {
// this is to stop successive clicks on ratings,
// although the server should still validate to make
// sure only one rating is sent per game
if($(this).hasClass('inactive_for_click')) return false;
$(links).addClass('inactive_for_click');
// get the index of the link relative to the rest, add 1
var index = $(links).index(this) + 1;
$.post("../includes/process/rating.php", {
id: "<?php $game_id ?>",
type: "game",
rating: index
}, function(data) {
$('#status').html(data).fadeIn("normal");
// unbind links to disable further voting
$(links).unbind('click');
});
});