JQuery onclick issue when calling a function from the parent page - php

I'm having a problem..
Actually I do have an issue when sending a value from a child page to the parent page.
I'm actually loading a page via JQuery and that page is getting refreshed to display new results, but one of these problems is that the function from the parent page doesn't get called from the child page.
Although this works perfect on Google Chrome, Opera and Safari, it doesn't seem to work on Firefox.
I heard Firefox doesn't manage events the same way as Safari or Google Chrome does?
I've been searching on answers for this but I couldn't find anything pretty much..
Alright, here's what I'm doing:
The child page calls another file which has all the functions that make my site work, this is what should trigger the function:
$like = "<a href='$comment_poster' id='$msgid' class='like'
onclick='parent.likecomment(this);'>Like</a>";
echo "$like";
And this is the function that gets fired from the onclick event which is located in the parent page (the function is in the parent page the onclick is in the child page):
This function is the one that receives the id from the child page to later on add the value to the database.
function likecomment(commentID)
{
event.preventDefault();
var likeid = commentID.id;
var author = ($(commentID).attr('href'));
// forming the queryString
var data = 'likeid='+ likeid + '&author=' + author;
if(likeid)
{
// ajax call
$.ajax({
type: "POST",
url: "likeprofmessage.php",
data: data,
beforeSend: function(html)
{
$(".word").html(likeid);
},
success: function(html){
$("#resultsprofcomments").fadeIn('slow');
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $row['1'];?>').fadeIn("slow");
$("#resultsprofcomments").append(html);
}
});
}
}
I've tried the Firefox console and I've received the error: event is undefined so this should be a problem on how Firefox manages events.
Again, any help is appreciated, thank you very much.

I think the following will work as long as you set the onclick handler inline in your HTML (as you did in your example):
<A href="..." onclick='parent.likecomment(event,this);'>blah</A>
<SCRIPT>
function likecomment(evt, commentID) {
evt.preventDefault();
var likeid = commentID.id;
// etc
}
</SCRIPT>
For event handlers not set inline in HTML, the standards compliant browsers (including FF) should automatically pass the event object as a parameter to your handler function. IE, up to version 8, anyway, uses a different event model and lets you reference event directly - really it is window.event but generally as with most window properties it works even if you omit window..
So if you assign your click handler on document ready (or onload) you can do this:
function yourOnloadFunction() {
document.getElementById('yourElementId').onclick = clickHandler;
}
function clickHandler(e) {
// check if event object was passed in, otherwise use window.event
if (!e) e = window.event;
// but how to get a reference to the clicked element?
// use the event object's target property, except (of course)
// in IE, which uses srcElement:
var elRef = e.srcElement ? e.srcElement : e.target;
// rest of your function here, e.g.
e.preventDefault();
}

You have managed to make a mess of your code, but try to change
onclick='parent.likecomment(this);'
to
onclick='parent.likecomment(this);return false;'
and then remove
event.preventDefault();
from your function likecomment(commentID).

Instead of using the in-line onClick, have you tried sending back a script that does something like
<Script>$('#{id}').click(function() {
var id = this.id;
likecomment(id);
return false;
})</Script>

Related

PHP printing out without leaving the page... How? [duplicate]

I have a website where I need to update a status.
Like for a flight, you are departing, cruise or landed.
I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works. I also don't want them to have and click a button.
If anybody knows how that would be done I much appreciate it!
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:
selector the existing HTML element you want to load the data into
url a string containing the URL to which the request is sent
data (optional) a plain object or string that is sent to the server with the request
complete (optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load(), where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
You can read about jQuery Ajax from official jQuery Site:
https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div.
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = function () {}; // do something here...
xhr.send();

how to change html button class and functionality?

Simply what I want is to to change the button class and value in order to change the button functionality.
what happening is that the value and the class are changed successfully BUT the functionality remain the same as for the old class
why?!
does the browser store the jquery code somewhere and load from it?! and how can i refresh it in that case??
here's piece of my code:
(I'm using Jquery Ajax with html and php)
var target_button; // global variable to store the target button
$(".activateButton").click(function(){
var serial_number = $(target_button).attr("id");
var cvc = $("#cvc").val();
$.ajax({
type: "GET",
url: '../ajax/tag.php',
data:
{
s: serial_number,
c: cvc
}
}).done(function(data)
{
var result = jQuery.parseJSON(data);
if (result == "1")
{
$("#message").text('Tag Successfully Activated');
$("#overlay_form").fadeOut(500);
$(target_button).attr("value", "Disable");
$(target_button).removeClass("popActivateButton"); //<---------- REPLACING THE CLASS
$(target_button).addClass("enableDisableButton"); //<----------
}
here's the buttons:
if($tags[$i]['Status'] == 1){
$button = "<input type=\"button\" class=\"enableDisableButton\" id=\"".$tags[$i]['SerialNumber']."\" value=\"Disable\"/>";
}
if($tags[$i]['Status'] == 2){
$button = "<input type=\"button\" class=\"popActivateButton\" id=\"".$tags[$i]['SerialNumber']."\" value=\"Activate\"/>";
}
When you use a selector it selects all elements that match at the time you execute the code. Previously called selectors - even if cached - do not dynamically update when new elements that match them are added to the page.
If you've bound event handlers to elements, then they're going to stay there until you a. remove the event handler(s), or b. remove the element entirely. Just changing the class isn't going to magically change the event handlers that are bound.
I'd suggest using event delegation instead:
$(document).on('click', '.enableDisableButton', function() {
//your code for enableDisableButton
}).on('click', '.popActivateButton', function() {
// your code for popActivateButton
});
With event delegation the selector is checked when the event is triggered, rather than when the code executes, so it will reflect changes to the page.
Note that I've used document in the code example above. However, you should instead use a selector for a static element (one that won't be removed) that will contain the elements you want to execute the event handler function for; the closer it is in the DOM structure to the dynamic elements the better.
Yes once event assigned you need to clear those previous events and bind new events to each.
suppose you have button and you have assigned click event now unfortunately you want to clear click event and something else you can do it as below,
$(SOMESELECTOR).unbind('previous_event').bind('new_event');.
For more search for jQuery bind and unBind.

load more jquery function that i want

i am using MVC and my design for my website is that there is header and body and footer,
every page in my website will have the same header and the same footer, but with different body
and for ever page there is a JS file contains the jquery calls
and for many many pages when it is opening, jquery call works and get data from database using ajax and put that data in that page
my question is : sense the jquery calls begins with $(document).ready, so when i open any page, all the jquery call starts, i don't want that, but i want just the jquery for that page which is opening to be loaded
example
this jquery just for a page
$(document).ready(function(){
$.getJSON("http://localhost/Mar7ba/Cell/getAllCountries/TRUE",function(data){
var select = $("#countrySelector");
var options = '';
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
select.html("<option>Select Source</option>"+options);
});
});
and this jquery for another page , but it is loaded when i load the first page
$(document).ready(function(){
$.getJSON("http://localhost/Mar7ba/Type/getAllTypes/TRUE",function(data){
var options = '';
options+="<option>Select Type</option>";
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
$("#addPlace #apTypeSelect").html(options);
});
});
Test for the existence of the elements you're operating on, before you fire off the AJAX method. For instance, in your first example:
$(document).ready(function(){
var select = $("#countrySelector");
if (select.length) { // must test .length; 'select' always exists even if it's empty
$.getJSON("http://localhost/Mar7ba/Cell/getAllCountries/TRUE",function(data){
var options = '';
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
select.html("<option>Select Source</option>"+options);
});
}; // end if
});
If you don't want a script to run on a page then either:
Don't put it on the page in the first place or
Wrap it in a conditional that checks if running it would be appropriate for the current page
I think if you will put all the startup functions of all pages in document.ready then function will become too lengthy and readability will be effected. You should write different start-up function for each page and call them from page on loading , in this your code will remain simpler e.g.
In js file
function InitialFunctionOfPage1()
{//define all prerequisites}
function InitialFunctionOfPage2()
{//define all prerequisites}
and in each page you can relevant function on document.ready , ample for page 1
$(document).ready(function()
{
InitialFunctionOfPage1();
}

Javascript functions on same DIV not working

I have two Ajax functions that are on the same div, the first one executes when complete page is fully loaded and call the ccslider method, instead the second one checks which menu ID I clicked, on the menu, to load dynamically different contents for different pages.
I can see the content loaded (eg: pictures) but unfortunately I don't see them in the ccslider; it seems that the slider is not executed.
But I know that works just because if I test it, removing the swapContent() function and place my PHP code with the MySQL query inside my main page the pictures are loaded inside the working ccslider.
Any hint on how to fix this problem?
$(window).load(function(){
$('#sliding').slider({
_Options: {
imageWidth: 300,
imageHeight: 200
}
});
});
function swapContent(cv) {
var url = "testing_cover.php";
$.post(url, {contentVar: cv}, function(data) {
$("#sliding").html(data).show();
});
}
You might have to call the slider method again inside the swapContent() function. Try this.
function swapContent(cv) {
var url = "testing_cover.php";
$.post(url, {contentVar: cv}, function(data) {
$("#sliding").html(data).show();
$('#sliding').slider({
_Options: {
imageWidth: 300,
imageHeight: 200
}
});
});
}
I have no access to the kind of plugin you're using, but from what it seems, you're probably modifying the HTML structure needed for it's functionality. Try inserting the HTML to a wrapper inside the #sliding element as opposed to directly in it.

How to initiate javascript in jQuery ajax-loaded content in IE8

I'm facing a trouble with jquery ajax under IE8. I have a form which at the base level displays a list of few items, each with buttons to edit and remove. The list, along with those two buttons, is loaded via jquery ajax call. Although it works fine on Firefox and Chrome, on IE8 it won't trigger functions behind edit or remove buttons.
So basically, on a base page, jquery works and loads the list. Within that list tho, jQuery doesn't work as it won't trigger edit or remove functions
I have a similar problem with the modal window call. IE8 is able to open the modal window (content is loaded with jquery ajax) but won't trigger any function within the content of the modal
Example of a simple call
$('#form-modal').load('/form/' + path + '?id=' + id).modal();
This works on IE8 from the base page, but doesn't when triggered within ajax-loaded content
All js scripts definitions are being loaded in the <head> of the main base page. I tried adding definition to the ajax-loaded file header, but didn't help so it must be something else
Any ideas? If you need more details, will gladly provide
Let me show you the easiest example. Each item on the list loaded with ajax has a 'remove' button.
Remove
DeleteItem definition is in external lib.js file
function deleteItem(id){
$.ajax({
type: "POST",
url: "/ajax/deleteitem.php",
data: "id=" + id,
success: function(msg){
loadItemsList();
}
});
}
This is it... That simply doesn't work on IE8... Nothing happens, not even javascript error. Same thing works no problem on Firefox and Chrome
It would be nice if you show the event handlers for those buttons, since if you're using bind(); for example, it loads when the dom is ready, and your ajax call is made. That means that the dom elements loaded through the ajax call wasn't there when bind was called to bind the buttons.
The solution to this is to use live();
$(".button").live("click", function () {
// do stuff
});
I don't know what event binder you're using, but if you're using anything other than live, you could try live and it should work.
EDIT
Read my comment first on the alert(id), if your function doesn't run at all in IE8, try doing this instead. Give the link element the id instead like this
<a id="item_10" href="#">Remove</a>
Then somewhere in your javascript
$("document").ready( function () {
$("a").live("click", deleteItem);
});
function deleteItem (event) {
event.preventDefault();
var id;
id = $(this).attr("id").replace("item_", "");
//this will now provide you with the current id
console.log(id);
your ajax-stuff here..
}
This should work in IE8, no problem. You might wanna specify the selector though for the click event by giving all the delete links some class or something.

Categories