I've been wrestling with a problem that I just cannot seem to solve. I've got a web form that is built from a MySQL query that's run from PHP and returned to JQuery that displays a gallery of movies that the user can give a numeric rating. I'm wanting to send the form back to PHP for processing and writing to the database.
function loadGallery()
{
$('content').append('<form id="movieRatings" action="../php/saveRatings.php" method="post">).html();
$.get('../php/getMovies.php')
.done(function(data) {
var query = $.parseJSON(data);
for (var i = 0, len = query.length; i < len; i++) {
var galleryMovies = '<div class="movContainer">' +
'<div class="movie">' +
'<a title="' + query[i].mov_title + '" href="../' + query[i].mov_title + '.html">' +
'<h3>' + query[i].mov_title + '</h3>' +
'<img src="../imgs/' + query[i].poster_path + '" /></a>' +
'<input type="number" name="' + query[i].mov_title + '" >' +
'</div>' +
'</div>';
$('#content').append(galleryMovies).html();
}
$('#content').append('<input type="submit" value="Submit"></form>');
})
.fail(function() {
$('#content').html("Epic Fail!") ;
});
}
The form displays without any issues, but clicking the submit button doesn't even send the request for the "saveRatings" PHP file. I'm sure I'm missing something simple, I just can't seem to figure out what that is. My first thought was that it was because the gallery isn't part of the actual html, but from what I've read that shouldn't have anything to do with it.
And pointers/sugestions/insight would be appreciated.
instead of
$('#ID').click(function(){
// do something here
});
switch to
$(document).on("click", "#ID", function(){
// do smth here
});
Your first assumption was true, if the element is not part of the initial html, then any events bound to it won't work unless you go with my second approach. You can find more about this behavior in the jquery documentation.
L.E: same goes for the submit action, in case i was not clear with the click example:
$(document).on("submit", 'form#formID',function(){
// do smth here...
});
Related
I have a searchbar included with the livesearch.com functionality from ajaxlivesearch.com
The problem is when i click on a result nothing happens. I want to send a query and show a result page when i click on the result. Before i included the ajaxlivesearch funtion i just typed in a keyword and pushed enter and then my result page showed up, this happens with an query. But after i included the ajaxlivesearch funtion pressing enter was not an option anymore, nothing happens.
I think the problem is within these jQuery lines;
jQuery(".mySearch").ajaxlivesearch({
loaded_at: <?php echo $time; ?>,
token: <?php echo "'" . $token . "'"; ?>,
maxInput: <?php echo $maxInputLength; ?>,
onResultClick: function(e, data) {
// get the index 1 (second column) value
var selectedOne = jQuery(data.selected).find('td').eq('1').text();
// set the input value
jQuery('.mySearch').val(selectedOne);
// hide the result
jQuery(".mySearch").trigger('ajaxlivesearch:hide_result');
},
onResultEnter: function(e, data) {
// do whatever you want
// jQuery(".mySearch").trigger('ajaxlivesearch:search', {query: 'test'});
},
onAjaxComplete: function(e, data) {
// do whatever you want
}
});
I hope someone can help me out
Cheers!
Before you do anything, go to the ajaxlivesearch.js file, and find this line of code ->
// disable the form submit on pressing enter
form.submit(function () {
return false;
});
Basically it's disabling anything form happening when you press enter, which is kind of the opposite of what you're trying to do. So obviously you need to change it, ex.
$("#search_ls_query").submit(function(){
return true;
});
Now, (This is not an entirely vital addition but nonetheless, submit the form in the "onResultEnter" area that you add to your index page. Ex.
jQuery(document).ready(function(){
jQuery(".mySearch").ajaxlivesearch({
loaded_at: <?php echo $time; ?>,
token: <?php echo "'" . $token . "'"; ?>,
maxInput: <?php echo $maxInputLength; ?>,
onResultClick: function(e, data) {
// get the index 0 (1st column) value
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// set the input value
jQuery('.mySearch').val(selectedOne);
// hide the result
jQuery(".mySearch").trigger('ajaxlivesearch:hide_result');
},
onResultEnter: function(e, data) {
$("#search_ls_query").submit();
},
/* #search_ls_query is the id of the default form that is submitted when you press enter (Find in ajaxlivesearch.js)*/
onAjaxComplete: function(e, data) {
}
});
})
Now go to the ajaxlivesearch.js file and find this:
var wrapper = '<div class="' + ls.container_class + '">' +
'<form accept-charset="UTF-8" class="' + ls.form_class + '" id="' + ls.form_class + '_' + elem_id + '" name="ls_form">' +
'</form>' +
'</div>';
And add an action to this form as this is what is being activated when you press enter in the search bar. So make it this:
var wrapper = '<div class="' + ls.container_class + '">' +
'<form accept-charset="UTF-8" action="search.php" class="' + ls.form_class + '" id="' + ls.form_class + '_' + elem_id + '" name="ls_form">' +
'</form>' +
'</div>';
This way it actually has a destination to send the values to. So the name of the value being sent is "ls_query", so whatever you type in the bar will now be inserted into the value of "ls_query". Therefore, once you press enter and arrive at your new page, you can then use this variable to filter your search options, or whatever you need. For example, on your search page you could write:
$ls_query = secure($_GET['ls_query'],$mysqli);
$sql = "SELECT *
FROM users
WHERE username ='$ls_query'";
This took me a while to figure out as well. But if you're still looking for the answer, this worked for me. Let me know how it went!
I'll try to keep this simple and clear. I'm pretty new to using API's but I'm using the Flickr API to search for and display photos on my website based on a certain tag. For a simple, static web page this is quite simple and I've already got it working as intended. This is the jquery script I found to use:
$(function() {
var apiKey = 'MY_API_KEY_IS_IN_HERE';
var tag = '%23FFLIVE2014-09-03';
var perPage = '25';
var showOnPage = '6';
$.getJSON('http://api.flickr.com/services/rest/?format=json&method='+
'flickr.photos.search&api_key=' + apiKey +
'&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?',
function(data){
var classShown = 'class="lightbox"';
var classHidden = 'class="lightbox hidden"';
$.each(data.photos.photo, function(i, rPhoto){
var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
+ rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;
var thumbPhotoURL = basePhotoURL + '_s.jpg';
var mediumPhotoURL = basePhotoURL + '.jpg';
var photoStringStart = '<a ';
var photoStringEnd = 'title="' + rPhoto.title + '" href="'+
mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' +
rPhoto.title + '"/></a>;'
var photoString = (i < showOnPage) ?
photoStringStart + classShown + photoStringEnd :
photoStringStart + classHidden + photoStringEnd;
$(photoString).appendTo("#flickr");
});
$("a.lightbox").lightBox();
});
});
Create a #flickr div on a page and load that script, photos tagged #FFLIVE2014-09-03 would be displayed, if there are any. My problem is that the site/page I want to show the photos on is dynamic with data generated from a database. So website.com/page.php is the single page, in the database is data for a certain date and a performance that happened on it (For a band).
So what I'm struggling with is how to dynamically edit the tags searched for in the script. With the above script placed in my page.php obviously page.php?id=1 and page.php?id=261 will show the same photos, because the tags searched will be the same when in fact they should be different, based on the date for the data.
So, is there some way to do this? Generate the correct date tag to search for based on the database data? I can generate the correct tag inside the PHP file itself quite easily, just echo the first part of the tag then the date. But how would I do that in relation to the javascript? I gather it is possible to use PHP within Javascript but that would be outside the database, so it wouldn't know what it was generating.
I hope that makes sense!
I'm learning JavaScript but I want the following thing in my little (self-started) project as soon as possible.
Suppose the page of my website is www.mywebsite.com/myPage.html
Here is a scenario that 10 users are viewing myPage.html from my website. As I make any change to myPage.html from server (being admin), I want all viewers of myPage.html to see refreshed page with new changes taken effect just after I make any change in myPage.html. It should be very fast.
For this I think I'll have to create a button which will refresh the page myPage.html. As I'll make changes to myPage.html, I'll press that button and that button will reload every viewer's browser's page (myPage.html). And they will see the result of modified myPage.html in their browsers.
Kindly explain your answer properly, since I'm a beginner. Which Languages are needed for this?
i think the best option here would be some kind of push implementation / web sockets ... here are a few links to get you started in the right direction ...
Websockets : Using modern HTML5 technology for true server push
Push Notifications to the Browser With Server Sent Events
In the case of socket.io in client side(browser) subscribe every client with a particular channel and make the page reload with javascript when request from server via that channel is recieved. And in server you can broadcast message to that particular channel whenever you want to reload the page.
you can create an AJAX function that is executing in intervals(like every 10 seconds) and this function will connect to server to ask for any update from mysql, so if there's any updates! you notify the user.
so you should create a table in DB to be updated with page update info when you update a page.
AJAX(asynchronous javascript and xml ) is a technology connect to your server without having to use Forms to post, and you can refresh part of your page automatically.
now here is an example:
I wanted to create an online chat, so here is the code:
this code use ajax to post to ChatNotifyController.php to see if theres anyone online,if there's any it will notify the user.
//notify user if someone has or had send a message
setInterval(function(){
xmlhttp.open("POST" , "../controller/ChatNotifyController.php" , true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
if((xmlhttp.response).length > 4)
{
var friendName = (xmlhttp.response).replace(/^\s*$[\n\r]{1,}/gm, '');
var responseArea = document.getElementById( friendName + 'ChatArea');
var x = friendName ;
if(x.indexOf('.') > 0)
{
x = x.replace('.', '\\.');
}
var link = $('#' + x);
var input = $('#' + x + 'ChatInput');
var e = jQuery.Event("keydown");
e.which = 13;
if(link.length > 0)
{
link.click();
input.trigger(e);
}
else
{
var html = "<li><a class=\"onlineUserLink\" id=\"" + friendName + "\" onclick=\"chat(" + "'" + friendName + "'" + ")\" >" + friendName + "</a></li>";
html += "<div class=\"chatDialog\" title=\"'" + friendName + "\"' id=\"'" + friendName + 'ChatDialog' + "'\">";
html += "<div class=\"chatArea\"" + " id=\"'" + friendName + "ChatArea" + "'\">" + "</div>";
html += "<input class=\"chatInput\"" + " id=\"'" + friendName + 'ChatInput' + "'\" size=\"21\" onkeydown=\"chatController(event , '" + friendName + "' , '" + window.user + "')>" + "</div>";
window.onlineArea.innerHTML += html;
var THIS = $('#' + x + 'ChatDialog');
$(function() {
THIS.dialog({
stack: false
});
});
link.click();
input.trigger(e);
}
}
}
else
{
//alert("Error during AJAX call. Please try again #003");
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("user=" + window.user);
} ,5000);
I have jquery function that calls a php script some data from my mysql database, the jquery function is called as below :
$(document).ready(function(){
getTopFiveDeals();
When this runs it gets the data fine and builds some HTML and inserts it into the webpage. As shown below:
$('ul.special-list').append("<li><a href='#' class=restaurantItem restaurant= '" + item.estName + "' adddress='" + item.estAddr + "'><img src= " + item.img_link +
" width='60' height='60' alt='" + item.estName + "'><div class='img-det'><strong class='title'> " + item.title + " </strong><p> " + item.desc_short +
" <br>Expires: " + item.expiry_date + " </p><em class='price'>" + item.price + "</em></div></a><a href='dealDetail.html?id=" + item.id +
"' class='det-link'>Detail</a>");
The problem starts when i have a simple jquery function below. The function is not called instead the page reloads to index.html#
$("a.restaurantItem").click(function (event) {
alert('Hello');
}
Any help and or advice would be much appreciated.
Many Thanks
$("a.restaurantItem") is called once. It doesn't look for new elements. You need to use the event delegation syntax of .on() to match those dynamically created elements:
$('ul.special-list').on('click', 'a.restaurantItem', function(e) {
e.preventDefault(); // To stop the link from redirecting the browser
});
You'll need delegated event handlers for dynanic elements, and to prevent the default action on anchors (to avoid scrolling to top or following the href)
$('ul.special-list').on('click', 'a.restaurantItem', function(event) {
event.preventDefault();
alert('Hello');
});
use .on() this way
$(document).on('click',"a.restaurantItem",function (event){
event.preventDefault();
alert('Hello');
});
I created an image sliding gallery where when an user presses the left/right arrows one image slides out and the new image slides in. It worked good.
All the related images and descriptions went in my PHP file. Now I want to have some new images and I found that adding and modifying this content took me longer than it should.
So I decided to remove all the image markup and have a JSON file for the images:
Here is the code that I am using in order to retrieve the data and to inject it in the DOM
$.getJSON('data.txt', function(data) {
var len = data.length, i; for (i = 0; i < len; i += 1) {
$("#image_container").append(
'<div class="image_frame"><img class="image" src="' + data[i].image + '" width="620px" alt="' + data[i].alt + '">
<div class="caption"></div><div class="innercaption"><p><span>' + data[i].category +
'</span> |' + data[i].title + '</p></div><div class="caption2"></div><div class="innercaption2">
<p><span>Description</span> | ' + data[i].description + '</p></div></div>' );
};
});
It runs at the start of document ready - But now the sliding arrows do not work, but no errors are generated.
My guess is that it would be because the content is created at the same time as the slider code. So, they can't see each other.
Is there a way to fix this (maybe run the getJSON in a way that the slider code can see it)?