What am I trying to accomplish is to display a text message on a web page after I click a text. The new text should replace the text that I clicked. The new text should be the value of the id attribute. The hyperlink is meant to go away after the first click (and become unclickable).
Here is one of my attempts:
Apasa textul 1
<script type="text/javascript">
$("#id").on('click', function() {
document.getElementById("Ana").innerHTML = "<span> Ana </span>";
});
</script>
The tag that should be used to replace the <a> tag is <span>.
I expect to display Ana after I click Apasa textul 1
Any help will be appreciated, thanks.
There will be quite a few different ways to do this, but if you want to employ an inline function call, you could declare a custom function called swapTag() (or whatever you like) which will generate a new <span> tag, then fill it with the original tags id value, then replace the original dom element with the newly generated element.
function swapTag(el) {
let newEl = document.createElement('span');
newEl.innerHTML = el.id;
el.parentNode.replaceChild(newEl, el);
}
Apasa texul 1
Although you have stated that you wish to replace the <a> tag with a <span> tag, if you want to replace the <a> with pure text, this will work too:
Apasa texul 1
There isn't a great deal of context to the question, so I don't know how much utility your project actually requires. Inline function calls may be an ugly choice -- using a listener may be a cleaner way.
I'll add an alternative that will use Jquery and an event listener (so that you you aren't muddying up your dom with inline function calls ...again, it is hard to give you a "perfect" answer because we don't know much about your application).
$(document).ready(function() {
$('a[href="#"][id]').click(function(){
let oldEl = this,
newEl = document.createElement('span');
newEl.innerHTML = oldEl.id;
oldEl.parentNode.replaceChild(newEl, oldEl);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Apasa texul 1
Apasa texul 1
Apasa texul 1
And again, if you want to just swap the <a> tag for text, this is the jquery-listener version (listening for the click of an <a> tag with an href value of # and an id attribute containing anything):
$(document).ready(function() {
$('a[href="#"][id]').click(function(){
this.outerHTML = this.id;
});
});
On you PHP you must do this (put this code in the top of the page):
<?php
if(isset($_POST['name']))
{
echo $_POST['name'];
exit;
}
?>
On JS:
$('#Ana').click(function()
{
var name = $(this).attr('id');
$.ajax(
{
type: "POST",
url: "index.php",
cache: false,
data: {'name':name},
dataType: 'text',
success:function(result)
{
alert(result);
}
}
)
});
The alert will show you the echoed value by PHP. From there do as you please... something like $('p').html(result);
Because you are doing an ajax call, you cannot rely on that inline code you wrote, since the page is not being entirely refreshed. That code executes when you first load the page, but because when that happens you are not passing parameters via POST (normally) in the initial statements "else" is always executed.
When calling ajax if you do not perform "exit;" in my code above, you would receive the entire page in the result. That's why the code must be at the top of the page, and an exit must be called after.
You don't need all those stuff.
If i understand the whole, you want, when the link is clicked, to:
perform an AJAX call
replace the whole link by its ID property, no matter the call does
Apasa texul 1
is the fastest way, considering your AJAX call would be in performAjaxCall() .
Apasa texul 1
<p><?php if(isset($_POST['name']))echo $_POST['name'];else echo 'rusu';?></p> /** 2nd line **/
The 2nd line isn't meant to be executed after an AJAX request, it only gets executed when the entire page is requested normally.
To have the wanted results you may :
In the JavaScript part, when attaching the click handler you'll need to prevent the default behavior of the a element (redirects to wathever the href attribute is, if it's # the page gets scrolled to the top in most cases). Also, to distinguish that the request is an AJAx request you may use a POST variable, set to 1 for example, to check it in the server side.
In the PHP part, check if the $_POST['isajax'] (the variable that should tell us we have an AJAX request) and $_POST['name'] are set and $_POST['isajax'] equals 1 then echo the $_POST['name'] and halt the script. Also, these checks are likely to be the put in the top of the PHP file.
The JavaScript part may look like :
$('#Ana').click(function(e) {
e.preventDefault(); /** prevents the link's default behavior **/
var name = $(this).attr('id');
$.ajax({
type: "POST",
url: "index.php",
data: {
isajax: 1, /** means we have an ajax request, it's not that **/
name: name
},
success: function(response) {
alert(response)
}
})
});
and the PHP part (top of index.php page) ould look like :
if(isset($_POST['isajax'], $_POST['name']) && $_POST['isajax'] == 1) {
echo $_POST['name'];
exit; /** no further lines are executed **/
}
Related
So, a little context: I'm trying to do an ajax call to a webpage in the same domain to get a telephone number to show up as soon as I specify the client on the first page. I do get the data but it seems like not the whole page is loaded in.
I need this:
<div id="1">
<div id="2">
<a id="ineedthis"></a>
</div>
</div>
but instead it's giving me this:
<div id="1">
</div>
This is a website that I'm writing a script for, since I can't edit the source code. This is managed from our ERP program and is pretty limited in customizability.
My best guess is that the target webpage is also still loading in the information from the database, but my ajax call returns the webpage before that happens.
Here is my js code:
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
console.log(href);
if(href !== "https://52134.afasinsite.nlundefined"){
$.ajax({
url:href,
type:'GET',
success: function(data){
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
}
});
}
}
setInterval(updateClasses, 1000);
I'm running this once per second to check for a change in the input field on the first page, I don't know if there is a better way for this?
Firstly, you could try running the script/function once a change has been detected.
Something along the lines of :
$('input[name="{inputFieldName}"]').on('change',function(){
updateClasses();
});
//You can also use "keyup" instead of "change", depending on the type of action that you are looking for.
For the Ajax, you could try using Promises. Basically, set up the ajax call and then set a ".done" case for the ajax call has been completed and received some result. A ".fail" can also be used to catch non-code related issues.
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
var getPhonePromise = $.ajax({
url: href
});
getPhonePromise.done(function(data) {
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
});
getPhonePromise.fail(function(errRes) { console.log(errRes);});
}
Im currently struggling with an AJAX related problem on a website.
The goal is as follows:
There is a "simple" HTML page containing some links and content.
If you click on a link I want to open the file that gets includes with the link (from href) within a new div overlayed to the page. The content from the page is of course loaded with AJAX into the new div (the overlayed one).
Within this new overlayed div I want to add some JS code which in general already works.
The problem anyway is that the DOM elements within the page loaded per AJAX cannot be accessed in a way that is comfortable to work with, in my specific case.
I got following piece of code so far:
$$('.add-exercise').addEvent('click', function(e) {
var request_exercise_add = new Request.HTML({
'method' : 'post',
'url' : e.target.get('href'),
onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I know I can access the elements returned within responseElements but the logic on the included website is somehow quite complex and therefore it should be
possible to add the JS within the HTML code in the dynamically loaded page.
Notice that the JS also cannot be added to the head section because it would not know the elements that are loaded after the dom-ready event.
have you tried iframe ?
or the website that you are trying to add does not have PPP cookie and AllowContentInIframe .. ?
If you want to add the script inside the ajax request you need evalScripts: true and you should remove the quotes around the request options.
$$('.add-exercise').addEvent('click', function (e) {
var request_exercise_add = new Request.HTML({
method: 'post',
url: e.target.get('href'),
evalScripts: true,
onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I don't know what is the content of the response but you might also want to use Mootools's .set() instead of innerHTML to append new elements (if you are not doing that yet). Maybe worth to check Dimitar's answer here about that.
I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.
I want to make a few divs on the same page work similar to iframes. Each will load a URL which contains links. When you click on those links I want an AJAX request to go out and replace the div's html with new html from the page of the clicked link. It will be very similar to surfing a page inside an iframe.
Here is my code to initially load the divs (this code works):
onload:
$.ajax({
url: "http://www.foo.com/videos.php",
cache: false,
success: function(html){
$("#HowToVideos").replaceWith(html);
}
});
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$("#HowToProjects").replaceWith(html);
}
});
This is a sample of code that I'm not quite sure how to implement but explains the concept. Could I get some help with some selectors(surround in ?'s) and or let me know what is the correct way of doing this? I also want to display a loading icon, which I need to know where the right place to place the function is.
$(".ajaxarea a").click(function(){
var linksURL = this.href; //
var ParentingAjaxArea = $(this).closest(".ajaxarea");;
$.ajax({
url: linksURL,
cache: false,
success: function(html){
$(ParentingAjaxArea).replaceWith(html);
}
});
return false;
});
$(".ajaxarea").ajaxStart(function(){
// show loading icon
});
Assuming you want to listen to click events for all anchor tags inside all elements with class ajaxarea, then your selector works fine:
$(".ajaxarea a").click(function(){ .. });
And this line of code, while not a selector (you're just accessing a property on the DOM element that was clicked), should work fine as well:
var linksUrl = this.href;
As for ParentingAjaxArea, you'll need to use $(this).closest() with a selector to determine which parent you want, but it's hard to give a specific example without knowing your HTML structure. It looks like you want ParentingAjaxArea to be either the element with id #HowToProjects or #HowToVideos, so you could write:
var ParentingAjaxArea = $(this).closest("#HowToProjects, #HowToVideos");
As for the loading dialog, I think this answer explains a good method (using ajaxStart and ajaxStop).
Edit: I also noticed you're using the click event--If you plan on being able to attach event handlers to links that will be inserted into the DOM via AJAX later, look at delegate or live.
$(".ajaxarea a").live('click',function(e){
e.preventDefault(); //*
var URL = $(this).attr('href');
var parentFrame = $(this).parent(".ajaxarea"); //**
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.replaceWith(html); //***
}
});
});
* - added preventDefault to prevent click action (see e in function's arguments)
** - instead of closest, i used parent – like it more for it's descriptive qualities
*** - the var containing parent AJAX frame should be jQuery object, no need to wrap it in $(..)
This should work fine, but beware, it's untested.
edit:
You probably need a live (okay, I'm sure you need it). what click() does it's that it adds to all elements at the time in DOM an onClick event. What live() does, it's that it waits for any change in DOM and runs used selector (.ajaxarea a) again and if it fits for any of new elements, it adds the action. In pseudocode, it does basically this:
DOM.hasChanged{
$('selector').click(..)
}
I used this example for my own web page:
http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp
It works quite well and uses hash tags and jQuery.history.js for the history of your browser. It works very nice, because you can let something like a media player just continue playing. Take a look at my own site elsewise, where you can find the javascript file: ajaxpages.js. I haven't used live(), but maybe I should.
Figured it out! The problem was I was using the function ".replacewith()" which was removing my AJAXed div(class="ajaxarea") entirely instead of replacing the content. The proper function to use here was ".html()".
Here is my working code to make an AJAXed div work like an iframe:
//onload to initialize the div
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$('#HowToProjects').html(html);
}
});
$(".ajaxarea a").live('click',function(e){ // must use live instead of .click()
e.preventDefault();
var URL = $(this).attr('href');
var parentFrame = $(this).closest(".ajaxarea");
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.html(html);
}
});
});
I'm trying to do a pretty simple thing, I believe. I need to popup a success confirmation dialog after a user clicks to add someone to his friends list. Simply there's an add link on the page with the url (mysite.com/add/friendname). I needed to make issue this request asynchronously so I used jQuery.ajax built-in function to send the request. Take a look at the following code:
$(document).ready(function() {
$('.track_links').click(function() {
if (confirm("are you sure you want to track <firstname lastname>?")) {
$.ajax({
type: "GET",
url: this.href,
success: function() {
alert("Congratulation! you're now tracking <firstname lastname>");
},
error: function() {
alert("Oops! An error occured, plz try again later!");
}
});
return false;
}
else {
return false;
}
});
});
Now, here's what I need to do in short:
1- I need to use an already designed Html form as the success or failure confirmation message, instead of just alerting!
2- I also need to replace a placeholder (###username###) on that html page with the actual user name (firstname space lastname) which is the value of another field on the document. How to manipulate this html before poping it up on the client?
p.s: My Html/Javascript skills is totally awesome ;) (well, not really)!
For the first part
You can use the
show
function to show a div in the ajax success function.
$("#divResult").show();
if divResult is the id of the div to be shown
For the second part
you can get the value of first name and last name using
$("#txtFirstname" ).val();
and
$("#txtLastname" ).val();
if your first name text box id is txtFirstname and last name text box id is txtLastName
This is how I setup an Acknowledgement dialog, which could quickly be modified to be a confirmation for an action like yours.
http://professionalaspnet.com/archive/2009/06/02/Displaying-a-Confirmation-Dialog-with-the-JQuery-UI-Dialog.aspx
For the Form, I would suggest the html() Method, which injects raw HTML you have to provide. Since you already have it, you can give it to the Method via parameters.
For the Placeholder Part, I would suggest the val() Methods, coupled with Javascript's built-in regex functions.
If your placeholder is "###firstname###", then you should try something like
var firstname = jQuery('input#firstname').val();
var lastname = jQuery('input#lastname').val();
var text = jQuery('span#ThePlaceMyPlaceholderIsAt').text();
text = text.replace(/\#\#\#firstname\#\#\#/,firstname);
text = text.replace(/\#\#\#lastname\#\#\#/,lastname);
jQuery('span#ThePlaceMyPlaceholderIsAt').text(text);