Making a function affect a element in another page - javascript

I made a function that is invoked for the lack of better words from a page, lets call it Page1, the function is called when a button is clicked, at the end of said function it calls another one that creates (or should seeing I haven't been able to test it) a html and appends it to a div with a #lista id.
The problem is that this div is another page (Page2), so I don't know if there is some syntax like in ajax where you specify where you want those values to go, so basically page 1 calls a function (on another file just in case) that function calls another and the result of that function goes on Page1 (another file, again just in case)
Here is my jQuery/JS code to further illustrate:
$("#btnAceptar").click(function() {
var idlab = $('#txtNumLab').val(),
capacidad = $('#txtCapacidad').val(),
carrera = $('#txtCarrera').val(),
ubicacion = $('#txtUbicacion').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'addLab',
'pIdLab':idlab,
'pCapacidad':capacidad,
'pCarrera':carrera,
'pUbicacion':ubicacion},
dataType: 'json',
success: function(response){
alert('exito')
agregar();
}
});
});
This function should affect a element with id #Lista on Page2.
function agregar(){
var div = $( "#lista" ).append( "<div class='box'>
<p>Lab #'numero'</p>
<p class='info'><a href='#' id='lnkInfo'>Info</p></a>
<p class='info'><a href='reservarLab.html'>Reservar</p></a>
</div>" );
div.id = querySelectorAll('#lista > div').length +1;
var numero = div.id;
$('#numero').append(div);
}
Thanks a lot in advance!

Yes you can get content from another page using jQuery:
Ajax request gets the entire file, but you can filter the content once it's retrieved:
$.ajax({
url:href,
type:'GET',
success: function(data){
$('#content').html( $(data).find('#IDofDivToFind') );
}
});
Second Approach (Untested)
You can use JQuery .load() method:
$( "#content" ).load( "ajax/test.html div#content" );
Reference:
http://api.jquery.com/load/

Related

How to generate a button with its own js function?

Well I have data retrieved from ajax, I need to parse it in order to generate inputs with different <input> values. While clicking on <a> that should get near standing input value and go to ajax
<script type="text/javascript">
function proceed() {
var ID = document.getElementById('btnid').value;//probably that`s the wort way, because all of `<a>` buttons would have same id
//ajax with ID to proceed further
}
$.ajax({
async: false,
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
complete: function (res) {
for(var i = 0; i < 10; i++) {
document.getElementById('nie').innerHTML = "
<ul class=\"somec\">
<li class=\"liclass\">
</input id=\"btnid\" value=\""+res.response[i].animal+"\" class=\"thatclass\" onclick=\"proceed();\"></input>//different values
<a id="clicker" onclick="proceed()"></a>//clickable link
</li>
</ul>
";
}
});
</script>
<html>
<div id="nie">
</div>
</html>
Any help or advises for solution ?
You cannot have more than one id in a single DOM -- only one unique id is allowed. Since jQuery is used here, you can take advantages of the other methods and API it provides.
First of all, I would move the loop to success handler of $.ajax because that ensures that I have data returned from the server.
As for "appending" input and anchor pairs, use $.append. What you're currently doing is just updating #nie with the last element's data in the loop.
For events, delegate the clicks on anchors. This is better because you might continue adding more elements, so you have to go through binding them to an event.
And please, don't set async to false in $.ajax settings. This has unexpected results and makes the browser slow to point that freezes and crashes. jQuery ajax async: false causes a strange warning?
$(function(){
var $nie = $('#nie');
// Delegate the click event
$(document).on('click', '.clicker' function(){
var id = $(this).siblings('input').val();
// Use id in upcoming AJAX request.
});
$.ajax({
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
success: function (res){
$.each(res.response, function(i, r){
$nie.appeand('<ul class="somec">\
<li class="liclass">\
<input value="'+ r.animal+ '" class="thatclass"/>\
<a class="clicker"></a>\
</li>\
</ul>');
});
}
});
});

Turning jquery into an includable, callable function

I'm so frustrated! As an ok PHP developer I can't get my head around the simplist of jquery problems!
I have recently moved my HTML jquery include to the end of the HTML body, instead of in the head to improve google pagespeed score.
This has broken some jquery which is used for simple comment voting. This was written badly as it repeats for every comment.
<div id="voterow-19907" class="commentfooter">UP</a> | <a id="comment-vote-down-19907" href="#" rel="nofollow">DOWN</a></div>
<script>
$("#comment-vote-up-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=up",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
$("#comment-vote-down-19907").click(function() {
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v=19907&d=down",
success: function(data){
$("#voterow-19907").text("Thank you for your vote")
}
});
return false;
});
</script>
Since moving the jquery include to the bottom of the page this naturally doesn't work.
What I'm trying to do is turn the above code into a mini function I can include after the jquery include, then pass the ID and VOTE-DIRECTION to the function from the HTML a hrefs using the jquery DATA- attribute.
Any help would be greatly appreciated. I'm running out of hair!
I think, repeated codes will hurt your page than placement of JQuery file.
You can solve this problem using more general event listener. Remove all listeners inside code (all of them) and append the code below after Jquery include.
$('[id^=comment-vote]').click(function() {
var elementId = $(this).attr('id');
var elementIdParts = elementId.split("-");
var voteType = elementIdParts[2];
var id = elementIdParts[3];
$.ajax({
type: "GET",
url: "/ajax.php",
data: "a=rv&v="+id+"&d="+voteType,
success: function(data){
$("#voterow-"+id).text("Thank you for your vote")
}
});
return false;
});
$('[id^=comment-vote]") selects all elements which have id starting with "comment-vote". If user clicks one of these elements, event handler gets id of elements, split into parts like "comment", "vote", "up", "19900". 2nd part is voteType and 3rd part is ID of row. We can use these variables while generating/operating AJAX request.
I didn't try the code but the idea behind that would be beneficial for you.
To really give a great working answer, I would need to see your an example page / the exact structure of your html, but here's what I have for you.
In a script file that you include after jQuery, you can include something similar to the below code assuming your html is as follows:
<div id="voterow-1" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
<div id="voterow-2" class="voterow">
<p class="voteresult"></p>
<a class="upvote" href="#" rel="nofollow">UP</a>
<a class="downvote" href="#" rel="nofollow">DOWN</a>
</div>
Having the class of upvote and downvote makes it easy to target these elements in jQuery:
// After jQuery is loaded, the function passed to ready() will be called
$(document).ready(function () {
// bind a click event to every direct child with the upvote class of an element with the voterow class
$('.voterow > .upvote').click(function (event) {
// get the voterow parent element
var $parent = $(event.target).parent();
// use regex to strip the id number from the id attribute of the parent
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
// call your ajax function
vote(id, 'up', $parent.find('.voteresult');
});
$('.voterow > .downvote').click(function (event) {
var $parent = $(event.target).parent();
var id = parseInt($parent.attr('id').match(/^voterow-(\d+)/)[1]);
vote(id, 'down', $parent.find('.voteresult');
});
function vote(id, direction, $resultElement) {
$.ajax({
type: "GET",
url: "/ajax.php",
// here we have the id and the direction needed to make the ajax call
data: "a=rv&v=" + id + "&d=" + direction,
success: function(data){
$resultElement.text("Thank you for your vote")
}
});
}
});
Here is a demo: https://plnkr.co/edit/ECL376hZ3NOz8pBVpBMW?p=preview

Use one ajax call for different page and div?

I use this code to make ajax call to change the content of div in main page without reloading the page :
function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}
and I call it like that :
<p><a onclick="ajaxcall()" >Create</a></p>
The issue is very complicated because I have to call 4 pages in the same div :
create.hmtl ; update.html; delete.html ; read.html
Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :
create.html :
<div id="container">
....
</div>
<div id="container-1">
....
</div>
So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?
Edit
To explain more my problem, I have 4 options (create/update/delete/read) with 4 pages, and in every page they are 2 div and 2 contents for 2 forms, I should change div content of every option(CRUD) for every form in webpage!
form -> ajax call content -> create.html -> div:container
form-1 -> ajax call content -> create.html -> div:container-1
form-1 -> ajax call content -> update.html -> div:container-1
You can add those as parameters to the function and make it like below
function ajaxcall(url, data, targetDivId)
{
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
$("#"+targetDivId).html( returnedData );
}
});
}
For your scenario:
I assume that even the AJAX url may change as currently it's pointing to create.php. In case it's same then you can avoid tht parameter.
<p><a onclick="ajaxcall('/create.php', {} , 'container-1')" >Create</a></p>
<p><a onclick="ajaxcall('/update.php', object2 , 'container-2')" >update</a></p>
<p><a onclick="ajaxcall('/delete.php', object3, 'container-3')" >Delete</a></p>
Following mohamedrias' answer, if you also needed to process each alternate path in the CRUD use case differently, you can use global event handlers.
Don't handle when making the request:
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
}
});
Do handle seperatley for each alternate path in CRUD
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var url = settings.url;
if (url.match(/create.php/) && query.match(/container1/)){
$("#container1").find(".form-1").html( xhr.responseText );
}
});
You should also notice that the selector in my example implies that "form-1" is a Class and not an ID.
IDs must be unique but Classes can occur many times.
Following this rule, if you wanted to reuse the same form for each alternate path you can do so by addressing discrete elements in the form using unique class names for each element. The container Div must have a unique ID (as you have already done). But you must give that element context by chaining the selectors to first select the div using ID and then select the element using class.
If I understood it correcyly you want to provide an argument to the ajax calling function to apply the return content from "/create.php" to a different div.
function ajaxcall(id, path)
{
$.ajax({
type: "POST",
url: path,
success: function( returnedData ) {
$("#"+id).html( returnedData );
}
});
}
And in html you can set the id like
<p><a onclick="ajaxcall(this.id, "/create.php")" >Create</a></p>
var xhr = new XMLHttpRequest();
xhr.onload = function(){
var document = xhr.response;
var container = document.getElementById('container');
var container-1 = document.getElementById('container-1');
console.log(container, container-1);
// or
// var containers = document.querySelectorAll("#container, #container-1" );
//console.log(containers);
}
xhr.open('POST','/create.php');
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.responseType = 'document';
xhr.send();

Update div content using PHP and Javascript variables

I'm new to Ajax and need some help with this.
The idea is simple, I have a list of directories within the div 'list' and when I click on one of the directories, the div 'content' must list the content of this directory with a php function.
This is my html code:
<div id="list">
<ul>
<li id="directory_1" class="test">directory_1</li>
<li id="directory_2" class="test">directory_2</li>
<li id="directory_3" class="test">directory_3</li>
<li id="directory_4" class="test">directory_4</li>
</ul>
</div>
<div id="content">
<!-- Here you can see the folder content-->
</div>
This my jQuery + Ajax:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
It works, I arrive to list.php. And on PHP I have a function that lists directory content.
So how can I refresh 'content div' with the php function?
So if I click on directory_1 it will show /var/www/pg/directory_1 folders, and then if I click on directory_2 it will clear the 'content' div and will then list out the directory_2 folders.
Here is a jsfidde without the PHP code:
http://jsfiddle.net/e5v1dgpc/
Sorry for my English, if someone has a question I will try to clarify.
You could do something like this:
jQuery('#content').html('');
Which will just set everything inside the html to be blank.
Or I think you could use .empty() - http://api.jquery.com/empty/
If you called it at the start of your function then it should clear the div before repopulating it.
$(".test").click(function(){
var name = $(this).attr("id");
$( "#content" ).empty();
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
});
});
In order to set the target of your ajax you could do something like this with a success condition. You'd need to change it to display whatever content you want.
$.ajax({
url: 'list.php',
type: 'POST',
success: function(html) {
var divSuccess = $('#content', $(html)).addClass('updated');
$('#content').html(divSuccess);
}
});
This link might also be useful to you - jquery ajax load certain div
Instead of Emptying the 'content' div initially, you can empty it
OnSuccess of the Ajax post, as below:
$(".test").click(function(){
var name = $(this).attr("id");
$.ajax({
url: 'list.php',
type: "POST",
data: ({folder: name}),
success: function(){
$( "#content" ).empty();
}
});
});
Hope this is what you are looking for..

Using AJAX to Extract Data from IMDB API

I'm trying to get the year of a film given its title using IMDB's API and then appending the year in parenthesis next to the title.
There's some fundamental JS or AJAX thing that I'm screwing up. Any help would be much appreciated!
This is my code: jsFiddle
HTML
<ol>
<li>Jaws</li>
<li>The Lord of the Rings</li>
</ol>
jQuery
function getYear(title)
{
$.ajax({
url: "http://www.imdbapi.com/?t=" + title,
dataType: 'jsonp',
success: function(data){
var year = data.Year;
}
});
}
$("li").each(function() {
var text = $(this).text();
getYear(text);
$(this).append(" ("+year+")");
});
Your code is calling the AJAX function, but immediately going on to update the page before the asynchronous function returns. You need to include the code that updates the page in the callback to the AJAX function so that it executes when the data is ready.
I have reworked your code to this:
function getYear(title)
{
$.ajax({
url: "http://www.imdbapi.com/?t=" + $(title).text(),
dataType: 'json',
success: function(data){
var year = data.Year;
var text = $( this ).text();
$(title).append(" ("+year+")");
}
});
}
$( "li" ).each(function() {
getYear(this);
});
Which works successfully on this fiddle

Categories

Resources