Good day guys. So I'm trying to work on this simple jQuery program that triggers a function whenever and only whenever a select value has been changed. I plan to use this simple function in a more complex program once I make it work.
This is the code (it came from jQuery API website, and I modified it slightly to try what I wanted to happen):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>change demo</title>
<style>
div {
color: red;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<select id="selector" name="sweets">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
<script>
$( "#selector" )
.on('change',(function () {
$( "select option:selected" ).each(function() {
<?php header("Location:jcue.php")?>
});
})
.change();
</script>
</body>
</html>
What I want to happen is that, the page should only redirect to jque.php once the select input value has been changed. But what's happening in the program is that it automatically redirects to another page without even loading the current page itself. What's the problem? jQuery and Javascript are the unexplored foreign lands for me in web programming, and I know this is pretty basic to many web programmers, but I just need it (and I really have to start learning Javascript, AJAX, and jQuery when I get to have free time haha).
The complex program I'm going to use it to is a search results filtering program. But before I can do that, I have to make this simple program work.
Can anybody help me? Thank you. Answers will be greatly appreciated.
Try this instead::
$(function() {
$("#selector").change(function() {
location.href = "jcue.php";
});
});
This will fix your issue.
The problem is because your PHP gets executed as soon as the page loads - you cannot incorporate it as you have into javascript. Also, you don't need the each() within the handler. Try this instead:
$("#selector").on('change',(function () {
window.location.assign('jcue.php');
});
JavaScript is client-side script, while PHP is server-side. You are trying to trigger a PHP header redirect which should happen at server-time before it's sent to the client's browser. So this will not be working in that on change event.
Simply use:
$("#selector").change(function() {
window.location = "jcue.php"; //this can be URL as well
});
P.S. I noticed you have two "selected" options, mind tell why?
Not so good practice: to redirect using Javascript, since JS can be blocked
There were some syntax errors, here's a fix, just replace your code.
$( "#selector" ).on('change',(function () {
var str = "";
$( "select option:selected" ).each(function() {
window.location.replace("http://stackoverflow.com");
});
}));
Good Practice: use jquery ajax requests Jquery Ajax or redirect using standard php header function(which has to run before your html/js is loaded)
Good luck, learning programming. It's fun!
Related
I have this simple function in javascript to refresh a page after a set time.
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
Now after every refresh, I want it to call a PHP function, for example:
function writeName()
{
echo "Refresh me";
}
Is it possible to call the PHP function in JavaScript after every refresh?
Thanks
I'm afraid the answer is no. By the time JavaScript has been run on your page, the server side (PHP) has already finished processing. Your best bet is to accomplish what you need before the page load, or accomplish it with JavaScript alone.
If you are refreshing the page, you're effectively reloading it from the server, so any 'onload' events will fire again. The page will render again from scratch. You can call a PHP script using AJAX in some 'onload' Javascript listener if you like, though. e.g. with JQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function () {
setTimeout("location.reload(true);", 2000);
$.get('home.html', function(ret){
$('body').html(ret);
});
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
Beware of calling setTimeout() recursively though as it can make a page unresponsive over time. You may find this useful:
http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/
I have a file (lam.php) that displays a database-driven list of countries in Latin America. I would like to include it in various pages on my website as a convenient reference. But rather than simply include it, I'd like to use AJAX, so the users can decide whether or not they want to view the list.
So I'm learning how to work with AJAX. It sounds like I want to use jQuery + AJAX, using Post instead of Get.
But I immediately got hung up on an error on this line:
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
I don't see any errors displayed when I preview the page, but the error is highlighted in Dreamweaver. Nothing happens when I click the button, so there's obviously an error somewhere. Can anyone spot the error(s) in my script?
This is the entire script:
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
)
}
)
</script>
</head>
<body>
<button id="lam">Latin America<button>
</body>
You need to add a DIV to the HTML for the result to be displayed in. Then the callback function has to fill in the DIV with the response from the AJAX call.
Since your PHP script doesn't take any parameters, you don't need the data argument.
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php", function(response) {
$("#lam-result").html(response);
});
});
});
</script>
</head>
<body>
<button id="lam">Latin America<button>
<div id="lam-result"></div>
</body>
I have a problem, and I would like you to guide me to solve it if you do not mind ...
In my HTML source code had several pieces of css codes here and there. So I decided to put together into a file called principal.css and do the following in the head section
<link href="css/principal.css" rel="stylesheet" type="text/css" />
This has worked wonderfully!
My idea was to do the same with the javascript code in my HTML, but it has not worked. This is one of them:
$("[data-slider]")
.each(function () {
var input = $(this);
$("<span>")
.addClass("output")
.insertAfter($(this));
})
.bind("slider:ready slider:changed", function (event, data) {
$(this)
.nextAll(".output:first")
.html(data.value);
});
Is there some special way to do this?
My goal is that the page has the least amount of code, I leave well indented, documented and clean.
Greetings, I will await your answers in!
Please, excuse my english...
You need to wrap this in $(document).ready(...)
Also, it has unusual indentation. It would probably be better to format it like this:
$(document).ready(function() {
$("[data-slider]").each(function () {
var input = $(this);
$("<span>").addClass("output").insertAfter($(this));
}).bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first").html(data.value);
});
});
I personally don't like chaining so many commands like this in a row. It might be SLIGHTLY more efficient, but it makes it much more difficult to debug and fix problems. I personally would break the .each() and the .bind() into separate statements. But I suppose it's a matter of preference.
.ready() documentation
$(document).ready(function(){
// your code here
});
or
.load() documentation
$(window).on('load', function(){
// your code here
});
Place your js code in a separate .js file. Similar to how CSS is also placed in a separate file and then link it to your html file.
like so, in your html file:
<script src="somejsfile.js"></script>
And yes, you have to wrap your js code in a document.ready function so it can execute when the documents elements are finished loading.
For example:
$(document).ready(function() {
// Your JS code here
});
This is because the browsers HTML interpreter reads code from TOP to BOTTOM, so if your not setting a document.ready, the JavaScript will run before any of your document elements are loaded.
Head:
<head>
<link href="css/principal.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="myscript.js"></script>
</head>
myscript.js
$(function() {
$("[data-slider]")
.each(function () {
var input = $(this);
$("<span>")
.addClass("output")
.insertAfter($(this));
})
.bind("slider:ready slider:changed", function (event, data) {
$(this)
.nextAll(".output:first")
.html(data.value);
});
});
I would like to add that if you plan on putting your js code in a separate file which is a good idea. You should be aware that you will not have to use the...
<script>
//js code
</script>
...the script tags in a separate js file.
For a website I'm making for school, I'm trying my hand at using Jquery extensively for the first time, and even though I managed quite a bit so far, I'm stuck at two (most likely related) problems.
I'm aware that the upcoming case is somewhat long, but I feel it's necessary to submit all relevant code for everyone reading this to get a good image of what is happening.
Basically, the website is one index.html file, with the CSS thrown in, a few buttons, and one div with the ID content. I use this code to make this work:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
Then there is one content page, named search.html, which only contains a form that submits a search string to a search.php page (through ajax) that should then place the search results immediately back into a div called search_results in that same search.html file. The jquery that I use for this:
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("Functions/search.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
</script>
The issue that I'm having is as followed:
Before I had the first line of code: if ($('#content').innerHTML == " "){; implemented, I would open the site, main_text.html would nicely be loaded in, I could navigate to other subpages fine. But typing in something in the form field in search.html did not display any results (just typing should already trigger the function). When I hit the search button on this form, instead of seeing query results, the main_text.html file load again in the #content div. This made me assume that perhaps, somehow, that the code:
$(document).ready(function(){
$('#content').load('main_text.html');
});
was being called again unwanted. Hency why I implemented that check for whether innerHTML existed.
However, now, when I first load the page, the #content div does not load any initial content at all. (The section on the webpage just becomes black, like my page background) I have to click any button to get some content loaded again in my main content div. Also, when I now go back to the search.html, the typing anything to get results, like previously, still does not work. If I now hit the search button, I get the initial result again of what I'd see when I just opened the page: a blacked out #content div.
So somehow, the biggest issue is in the fact that the jquery to get results from my PHP do not seem to work. My problem with the content.innerhtml check might well be obsolete if the issue with the searchresults not displaying in the #search_result div on the search.html is fixed.
Anyone have any idea's what I could do to fix this. Or otherwise, what other approaches I could take for the kind of website I'm making. Since I'm trying to learn jquery here, better approaches are always appreciated, I'd rather learn myself doing this the right way and all. :)
Thanks for your time.
Few things to note here:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
In the above, you are testing to see if there is a space in the innerHTML of the element with an id of content.
jQuery uses .html() or .text() to make comparisons against the data being held within a container, so if you want to maintain using jQuery principles, change this line. Going along the same thought process, you are preparing an IF statement on an element before the document is actually ready and loaded.
You should move the document.ready function to the outside of the if statement. This will allow you to ensure that the element is available at DOM, and you can indeed perform checks against this element.
<script type="text/javascript">
$(document).ready(function(){
if ($('#content').html("")){
$('#content').load('main_text.html');
}
});
</script>
Also, while being readily provided and fully functional, I would recommend starting off using $.ajax instead of $.get / $.post. I have personal preferences as to why I think this, but I won't go into that, it's just that, personal.
$.ajax({
url: "Functions/search.php",
type: 'POST',
data: "search_term="+search_val,
success: function(data){
if (data.length>0){
$("#search_results").html(data);
}
});
Lastly, you should be using the GET method and NOT the POST method. Based on REST/SOAP practices, you are retrieving data from the server, and not posting data to the server. It's best practice to follow those two simple ideas. This isn't because web servers will have a difficult time interpreting the data; but, instead, it's to prepare you for working on larger scale application deployment, or future team-environments. This way everyone on the team has an expectation as to what method will be used for what purpose.
Anyway, long story short, you also leave semicolons off of the end of your closing }) brackets. While this is not an issue, nor will it cause flaws in your development, coding is all about uniformity. You've used the closing ; everywhere else, so try and maintain that same uniform design.
Best of luck.
hi i need to validate the next page before printing it ...
what i did is i used i frame in the first page and called the page i needed to print
but it fired the query in the first page which should have been fire in the second page after the submission or click of the button ...
so i need to fire the php function after the button click which calls a function in javascript how should i do this?
could anybody help me...
Okay, I am not familiar with your level of PHP knowledge, so I will start with some basics:
PHP is a server-side scripting language. It compiles in real-time when a page is requested. The server processes the HTML and PHP and serves an HTML only page to the browser. You cannot execute PHP code on the client side. There is no way to get PHP code running at the time of a button press without the use of AJAX. You could use AJAZ to make a request to the server at the press of the button and fill the iFrame with the output.
Hope that helps.
so i need to fire the php function after the button click which calls a
function in javascript how should i do
this?
I am not quite clear on why you would need to do this but here it goes...
In the button click handler you want to make an AJAX call. I use jQuery but you can use whatever framework or XMLHttpRequest function you wish.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function ButtonClickHanlder( e ) {
// Prevent the button from doing something it's normal functions(ie submit form if it is a submit)
e.preventDefault();
// Make AJAX Call
$.post("test.php", { call: "callMe" },
function(data){
alert("Data Loaded: " + data);
}
);
}
$(function(){
$('#clicker').click(ButtonClickHanlder);
});
</script>
</head>
<body>
<a id="clicker" href="#">test</a>
</body>
</html>
Reference: http://docs.jquery.com/Ajax
The test.php page
<?php
if(isset($_POST['call']) && $_POST['call'] == 'callMe') {
callMe();
}
function callMe() {
echo "I am a php function. You rang?";
}
?>