How create link in jQuery? - php

I have a jQuery notification. When I click on the notification it should go the intended page.
In PHP we can achieve that by doing following.
$link = 22;
echo "Click to read more";
How to achieve such in JQuery? I have notification pop up and link variable ready.
var link = "home.php?destination=22";

You can create HTML element using jQuery
var link = "home.php?destination=22";
//Create anchor element
var anchor = $('<a />', {
"href": link,
"text": "Click to read more"
})
//Append the element
$('#dialog').append(anchor).dialog();
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="dialog" title="Basic dialog">
</div>

you can achieve it using window.location.href in java script.
<button onclick="myFunction()">Click me to read more</button>
<script>
function myFunction() {
window.location.href = 'home.php?destination=22';
}
</script>

Related

How to transfer JQuery variable into PHP variable in a modal window without page refresh

I am new to this client variable to server variable transfer process.
Essentially I have a Google maps api function and have a marker on a map to represent a username in a users table (MySQL) of my PHP web app. When I double click on that map marker my Jquery function is popping up a modal and I am able to get the username in an id/name element (chosenUser) in a . However, I now need to be able to access this value in a PHP variable ($chosenUser) without any "submit" or page refresh, so that I can invoke my PHP function - getUserChannelID($chosenUser), and continue with the rest of the logic.
My disconnect is the ability to be able to access that value coming through on the id/name as #chosenUser and transfer it to a PHP variable $chosenUser without a "submit" or page refresh. All the code below is on the same page.
I am reading about the use of AJAX to do this in SF posts but since I quite the infant with AJAX I am getting confused on how exactly this can be done on the same page without a form "submit" or page refresh.
Can you please help correcting the code below so that I can get that value in #chosenUser to the PHP variable $chosenUser?
Here's my code all in the same PHP file.
<?php
require_once("classes/autoload.php");
$db = new Database();
....
?>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" ></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid" style="margin: 0 auto;">
<div style="height: 100%; position: relative; top:30px;">
<div id="map" style="height: 100%;"></div>
</div>
<div class="modal fade" id="showChannel" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Channel Preview</h4>
</div>
<div class="modal-body">
<div>
<input type="hidden" id="chosenUser" name="chosenUser" value="">
<!-- This is where I need help. How do I transfer that value I am getting for "chosenUser" above into the PHP variable $chosenUser - ideally the code in the next line would need to be executed -->
<?php $channelId = $db->getUserChannelID($chosenUser); ?>
.....
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script src="multiple_marker/oms.js"></script>
<script type="text/javascript">
var mapMarkers = [];
var infowindow = null;
var infowindowOpen;
var map, oms;
var gm = google.maps;
var markerIcons = new Array();
var gmarkers = [];
function getCoords() {
$.ajax({
url: "markers.php", // this markers.php provides the value of "Locations" array used below
type: "POST",
data: {
foo: "bar"
},
dataType: "json",
success: function (returnedData) {
console.log(returnedData);
if(!spiderify)
moveMarkerMap(returnedData);
//window.setInterval(getCoords, 10000);
window.setTimeout(getCoords, 2000);
}
});
}
function MarkerMap(json) {
var iconBase;
oms.addListener('click', function (marker) {
console.log('clicked');
});
if ((json.Locations.length > 0)) {
for (i = 0; i < json.Locations.length; i++) {
var location = json.Locations[i];
var username = location.username; // I am getting the value of username here
var myLatlng = new gm.LatLng(location.Lat, location.Long);
var marker = new gm.Marker({
position: myLatlng,
map: map,
username: username,
});
var infowindow = new gm.InfoWindow();
var div = document.createElement('DIV');
gm.event.addListener(marker, 'dblclick', (function (marker, div, infowindow) {
return function () {
$('#showChannel').modal('show');
$('#chosenUser').val(marker.username); //passing the value of marker.username to the modal input id/name="chosenUser"
};
})(marker, div, infowindow));
gmarkers[id] = marker;
}
}
window.map = map;
window.oms = omg;
}
gm.event.addDomListener(window, 'load', initialize);
</script>
Well, you can't exactly communicate between PHP and JS in the way you're thinking of. PHP is executed while the page is loading, before any content is displayed, before any javascript is even sent to the client, so it's impossible to do it as you wish.
What you can do is call a PHP script once the page is finished loading, using javascript. You can do this whenever you like, using a delay loop, when clicking a button, any way you can call your javascript function. That way you can send information from javascript to PHP, and when the PHP script finishes running it can report back information to javascript.
You want a variable from js in PHP, there are multiple ways of doing this, such as POST or GET requests. I'll post an example using POST, which is the same thing you'd use to send a form. You'll need to include jQuery for this to work.
JS
var myVar = "my info";
var myVar2 = "my other info";
$.post("myscript.php", {
info1: myVar,
info2: myVar2
}, function(answer) {
// answer will contain whatever the PHP script printed
// in this example answer will be "success"
alert(answer);
} );
PHP
$var1 = $_POST['info1'];
$var2 = $_POST['info2'];
if(!empty($var1) && !empty($var2))
{
echo "success";
}
It's up to you to implement it now.

I want to load 2nd div first and 1st div second

<div class="a">hello</div>
<div class="b">bye</div>
I have a one page website and I want a div to be loaded first and then the second one and... Can I do this just with html and css? Or it needs JavaScript or...
Just do it with Javascript:
Change your Body to <body onload="onloadFunction()">
Add style="display: none;" to your div Elements
Add following script:
<script language="javascript" type="text/javascript">
function onloadFunction(){
document.getElementsByClassName("a").style.display = "true";
document.getElementsByClassName("b").style.display = "true";
}
</script>
and change the order of the document. lines to which order you want to have it.
You can try this with something like.
$(document).ready(function() {
$(".b").delay(2000).fadeIn(500); //class b is on delay
});
Can't done with only HTML and CSS. Need to involve JavaScript or jQuery code too.
Yes you need javascript and I suggest jquery(javascript library).
More info at: http://www.w3schools.com/jquery/jquery_get_started.asp
And here is working example(just run with browser and click button):
<div class="a" style="display: none;">hello</div>
<div class="b" style="display: none;">bye</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.a').show();
setTimeout(function(){$('.b').show()}, 2000);
});
</script>

Jquery - Open a new window with content from the current page

I'm trying to create a 'print' button to open a new window and display a PHP Variable in it.
The code below is looped through the PHP script as many times as there are tickets, however I can't seem to get the correct number to display when the window opens (the number that displays in the print link is correct - but when the new window is opened it's incorrect).
<script type='text/javascript'>
jQuery(function($) {
$('a.new-window').click(function(){
var recipe = window.open('','PrintWindow','width=600,height=600');
var html = '<html><head><title>Print Your Ticket</title></head><body><div id="myprintticket">' + $('<div />').append($('#ticket').clone()).html() + '</div></body></html>';
recipe.document.open();
recipe.document.write(html);
recipe.document.close();
return false;
});
});
</script>
Print <?php echo $EM_Booking->get_spaces() ?>
<div style="display:none;">
<div id="ticket"><?php echo $EM_Booking->get_spaces() ?>
</div>
</div>
why not try something like this:
<a href="#" class="new-window">Print <?php echo $EM_Booking->get_spaces() ?>
<div class="ticket" style="display:none">
<?php echo $EM_Booking->get_spaces() ?>
</div>
</a>
<script>
jQuery(function ($) {
$('a.new-window').click(function () {
var btn = $(this),
ticket = btn.find('.ticket').html(),
recipe = window.open('','PrintWindow','width=600,height=600'),
html = '<html><head><title>Print Your Ticket</title></head><body><div id="myprintticket">' + ticket + '</div></body></html>';
recipe.document.open();
recipe.document.write(html);
recipe.document.close();
return false;
});
});
</script>
But much better solution would be to give a button a unique ID, and onclick open an existing (php-generated) page from the server passing that ID, e.g. /getBooking.php?id=123 and that page would output whatever's needed.

error message using modals for login

i need to show a dialog box if login failed. now i'm able to show the error line inside the form, but i need to show the error message using modals.
here's my code:
$sfAuth = new SfAuthenticate();
$sfHelper = new SfHelper();
$user = $_POST['txtUsername'];
$pass = $_POST['txtPassword'];
$checkUser = $sfAuth->checkUserJobSeeker($user);
if($checkUser)
{
$login = $sfAuth->loginJobSeeker($user, $pass);
if($login)
{
echo $sfHelper->redirect('forms/jobSeeker/HomeJobSeeker.php');
}else{
echo $sfHelper->redirect('forms/jobSeeker/formLoginJobSeeker.php?err=Invalid Username or Password');
}
}else{
echo $sfHelper->redirect('forms/jobSeeker/formLoginJobSeeker.php?err=Sorry, We Cannot found your Username');
}
i want to show the dialog box after redirecting to the login form.
can anyone help me please?
Have a look at this fiddle, it should work: http://jsfiddle.net/7PwWp/5/
As to launching the modal window on user error, you can add a condition:
<?php if(isset($_GET['err']): ?>
launchWindow('#message');
<?php endif; ?>
In the message box, you can put:
<p><?php echo (isset($_GET['err'])? $_GET['err']:''; ?></p>
To show a modal dialog box you'll need javascript. Check this previous SO question: How to create popup window(modal dialog box) in HTML). I would, similarly, recommend checking out jQueryUI which is an extension of the javascript library jQuery.
In 3 steps, here's how this works:
Include jQuery and jQueryUI library scripts in the page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"/></script>
Create the markup for the modal dialog to be displayed
Doesn't need to be fancy but note the id tag as jQuery uses that to know which element to display in dialog.
<div id="dialog" title="Basic dialog">
<p>This is the message inside the modal dialog.</p>
</div>
Show the dialog using jQueryUI
<script>
$(document).ready(function() {
$( "#dialog" ).dialog();
});
</script>
See a full working example here: http://jsfiddle.net/wjp94/3/
put this code on formLoginJobSeeker.php file
<?php
if($_GET['err'] == "Sorry, We Cannot found your Username")\
{
echo '<script> alert("Sorry Wrong Username Or Password");</script>'
}
?>
If you want to show dialog then you have to use jquery dialog
Add following code to your page;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"/></script>
<div id="dialog" title="Basic dialog" style="display:none">
<p>
<?php if(isset($_GET['err'])) echo $_GET['err'];?>
</p>
</div>
<?php if(isset($_GET['err']){ ?>
<script type="text/javascript">
$(document).ready(function() {
$( "#dialog" ).dialog();
});
</script>
<?php } ?>
if you want to see how your modal looks like check on this link
http://codebins.com/bin/4ldqp8p
Solved?
If not, here is my solution.
Redirect to sth like that (notice #run_modal):
`forms/jobSeeker/formLoginJobSeeker.php?err=YOUR_MESSAGE#run_modal`
and JS:
function detectModalParam()
{
var hash = $(location).attr('hash');
if (hash == '#run_modal')
{
YOUT_MODAL_FUNCTION();
};
}
$(document).ready(function()
{
detectModalParam();
}

using jquery, ajax and php to laod content on your site without reloading the whole page

I am a newby in ajax and php and I would very much appreciate it if you could help me out. Seeing that I only know a little bit javascript and php I really don't know how to remedy this problem could you help me please! I've been hunting down a fix but couldn't find any, hopefully my search will stop here. I'll try my best to be clear in my explanation.
I would like this:
load html page called ducks
to load into the myDiv area an html page called ducks.html.
I would also like that when I click on on this:
load a list of html links
I would like it to load an html page with a list of links that when clicked will load into the myDiv area without reloading the whole page.
And lastly I would like to set up the myphpscript php file. To load a page with a list of links that will appear in the myDiv area and when I click on one of those links it will load likewise into the myDiv area.
This is my code
<!-- This is your PHP script... myphpscript.php -->
<?php
$contentVar = $_POST['contentVar'];
if ($contentVar == "con1") {
include 'con2.html';
} else if ($contentVar == "con2") {
echo "<a href='con2'>View</a>";
} else if ($contentVar == "con3") {
echo "Content for third click is now loaded. Any <strong>HTML</strong> or text you wish.";
}
?>
<!-- This is the rest of my code -->
<html>
<head>
<script type="text/javascript" src="jQuery-1.5.1.js"></script>
<script language="JavaScript" type="text/javascript">
<!--
function swapContent(cv) {
$("#myDiv").html('<img src="loader.gif"/>').show();
var url = "myphpscript.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#myDiv").html(data).show();
});
}
//-->
</script>
<style type="text/css">
#myDiv {
width:200px; height:150px; padding:12px;
border:#666 1px solid; background-color:#FAEEC5;
font-size:18px;
}
</style>
</head>
<body>
<a href="#" onClick="return false"
onmousedown="javascript:swapContent('con1');">Content1</a>
<a href="#" onClick="return false"
onmousedown="javascript:swapContent('con2');">Content2</a>
<a href="#" onClick="return false"
onmousedown="javascript:swapContent('con3');">Content3</a>
<div id="myDiv">My default content for this page element when the page initially loads</div>
</body>
</html>
It sounds to me that if you want an external page to load when something is clicked, you need to perform an ajax GET or POST request, then print the results to the div:
http://api.jquery.com/jQuery.post/
If you just want to change the contents of the div to some other text, you can use something like jQuery.html: http://api.jquery.com/html/
<script>
$("#idForLink").click(function () {
var htmlStr = "The new text to show";
$('#myDiv').text(htmlStr);
});
</script>
Without using jQuery, your example above is sending self posts to echo contentVar which will always refresh the page.
See this fiddle for a jquery+css solution to your problem [NO PHP REQUIRED]: http://jsfiddle.net/bYNeg/
If you are simply grabbing HTML from another file I would use the load method, as its quick and easy:
$(document).ready(function(){
$('#myDiv').load("someFile.html");
});
For more extensive requests you can use Post and Get. They allow you to pass data with the URL request in order to affect the results that are returned. Obviously your requested URL would need to be PHP/ASP and handle the request in this case.
JAVASCRIPT:
<script type="text/javascript">
$(document).ready(function(){
// this is your mouse event (click) listener
$('.destination_div').on('click','a',function() {
var url = $(this).attr("href");
$('.destination_div').load(url);
return false;
});
});​
</script>
Make your HTML anchors simple, do not include inline javascript, because the on("click") handles it already.
HTML:
Your HTML with links

Categories