How to pass a variable with in jquery - php

I just started using jQuery in the past few days. I love how it makes functions simple. However because I am very new to using Javascript, I keep hitting a road block with one function.
I am trying to bind a couple functions together, but I'm not sure if I am doing it in the right order. What I want it to do is get a variable from a selector href='#from=xxxxx&to=xxxxx', with the xxxxx being a value printed out from a DB using PHP.
Then create a DOM window to display a form and insert those values into the hidden input fields. I have been stuck trying to figure out a way to pass those variables from the link to the form.
Here is my script:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://swip.codylindley.com/jquery.DOMWindow.js"></script>
</head>
<body>
<div id="msgBox" style="display:none"></div>
<?php $from="0"; $to="0";
for ($x=1; $x<=4; $x++){ $from++; $to++; ?>
user<?php echo $x;?><br>
<?php } ?>
<script type="text/javascript">
$("#msgBox").append("<form id='myForm' method='post' action='index.php'><div style='border:1px solid #cc0; width:300px;'><input type='hidden' value='<?php echo $from;?>'><input type='hidden' value='<?php echo $to;?>'>subject:<input type='text' name='subject'><br>message:<textarea class='mbox' name='msg'></textarea><br><input type='submit' value='submit'></div></form>");
$('.foo').click(function(){
$.openDOMWindow({
windowSourceID:'#msgBox',
height:135,
width:300,
overlay:0,
positionType:'anchoredSingleWindow',
windowBGColor:'#f9f5f5',
anchoredSelector:'.foo',
positionLeft:200,
positionTop:150
});
$("#msgBox").trigger();
return false;
});
</script></body></html>

In the handler for the click event on each link you can get a reference to the target link and extract the values from the href attribute and then set the values of the hidden fields in the form.
$('.foo').click(function() {
var href = $(this).attr('href'); // will contain the string "#from=0&to=0"
var from,to = ... // extarct from string by splitting by & or using url parse library
$('#msgBox').find("input[name='from']").val(from);
$('#msgBox').find("input[name='to']").val(to);
// rest of code...
});

Related

Add items to array without refreshing the page?

http://alpha.ripfy.com/
As seen in the following demo, I have a YouTube video that I want to be able to play while adding items to the array in PHP. Sadly, this isn't possible from what I've tried because the page refreshes every time I add an item to the array.
Would there be any way of achieving this without the page refreshing (forcing the video to restart?)
Code:
<?php
if (isset($_POST['playlist'])) {
$playlist = $_POST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_POST['name1'])) {
$playlist[] = $_POST['name1'];
}
?>
<form method="post">
<?php
foreach($playlist as $song) {
?>
<input type="hidden" name="playlist[]" value="<?php echo $song?>">
<?php
}
?>
<input type="text" name="name1"/>
<input type="submit" name="submit1"/>
</form>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
Thanks for helping me out!
if you need that these information be storaged in database or anything on server sider don't use the convencional form post, use AJAX with JQuery.
First create a div(container)to render the list content where you need the information apears:
<div id="list_musics"></div>
Then create a page(i.e. page.ajax.php) that will treat your request. If you need you can put the information in a database or anything you want by this page. This page must return the content you want to render.
HTML:
<input type="button" id="ajaxcaller">
JQUERY:
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
$.post(page.ajax.php,text,function(data){
//Render your content in the container created on HTML
$("#list_musics").html(data);
});
});
If you just need to show what you wrote on text input instead of storage or treat the information, you may just use JQUERY to render the information in the container you created.
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
// PUT THE TEXT RIGHT AFTER THE CONTENT THAT ALREADY EXISTS IN THE CONTAINER
$("#list_musics").append(text);
});
Take a look here to see the sencond option:
https://jsfiddle.net/wqLf65ox/
Here's my answer. That fully works. In this script, the server checks the presence of a name1 request (post or get). If exists, it returns the string posted (only) and if doesn't, it returns what already was there. And the post() method posts (gets) the data and appends to the container using innerHTML+= data + "<br>";
evaluate the code, it should be self explanatory.
<?php
if (isset($_REQUEST['playlist'])) {
$playlist = $_REQUEST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_REQUEST['name1'])) {
// if exists, return plain text responce. NOT HTML
$playlist[] = $_REQUEST['name1'];
echo $_REQUEST['name1'];
}
else{
?>
<html>
<head>
<title>Demo</title>
<script src="jquery.js"></script>
</head>
<body>
<script>
text= ""
function onUpdate(){
text = document.getElementById("name1").value;
}
function handler(data){
document.getElementById('container').innerHTML += data+"<br>";
}
function post(){
onUpdate();
$.get("index.php", name1="+text, handler);
}
</script>
<input type="text" name="name1" id="name1"/>
<input type="submit" name="submit1" onclick="post()"/>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<br>
<div id="container">
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
</div>
</body>
<?php };?>
Although, it works as intended, i don't see the point of using it. just plain js should work
You have to send your form using Ajax, eg. via jQuery.post() method.
After that you have to reload your container with list or add new item there with JavaScript.
Try using the $.post and $.get JQuery methods. One method might be to $.post back to a .php page that renders a container of html, then use $.get to retrieve just that html container and insert into the DOM.

PHP - Getting the value from a div based bootstrap element

I am fine getting the value of a form controls such as radio and select for example but with all of the additional non form based controls available for Bootstrap i haven't really seen many PHP examples how to use these.
So my main question is with pure PHP how would you retrieve the current selected item from a div and li based dropdown?
http://www.bootply.com/b4NKREUPkN
or a custom color picker plugin?
http://bootstrapformhelpers.com/colorpicker/#jquery-plugins
If you are submitting a form and handling the request using PHP, you will not be able to access the DOM in PHP (client vs server). If you can pull out the bits that you need using javascript, you can set the values on hidden form elements and submit.
<?php
// print out the value when the post is submitted
if (isset($_POST["extraInput"])) {
echo "hidden input is: " + $_POST["extraInput"];
}
?>
<html>
<head>
<script type="text/javascript">
function doSubmit () {
var extraValue = document.getElementById("extra").innerHTML;
var form = document.forms["myForm"];
form.elements["extraInput"].value = extraValue;
form.submit();
}
</script>
</head>
<div id="extra">Hello world</div>
<body>
<form id="myForm" action="" method="post">
<input type="hidden" name="extraInput" />
<input type="text" name="textInput" />
<button onclick="javascript:doSubmit()">Submit</button>
</form>
</body>
</html>

PHP - onClick doesn't seem to be working

I have series of dropdown boxes which can be selected by the user. I then want to have two different submit buttons that will do two different actions with the selected data. I am trying to code the submit button to run the selected php, but when I click the button does nothing. Any help is appreciated, my code is below. AFAIK the only relevant bits are my formSubmit function and the input tag near the bottom of the code.
edit: I have edited out a bulk of the code and left the pieces that I think are relevant. Please let me know if more info is needed.
<!DOCTYPE html>
<?php
require 'config.php'; // Database connection
//////// End of connecting to database ////////
?>
<html>
<head>
<SCRIPT language="JavaScript">
//Scripts
function submitForm(action)
{
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}
</script>
</head>
<body>
<div>
<?Php
//Beginning of Form
echo "<form method=post name='f1' action =''>";
//Dropdown boxes are here
//This line is what is not working:
echo "<input type='submit' value='Careers' onclick=\"submitForm('rt.php')\">";
echo "</form>";
?>
</div>
</body>
</html>
Not quite sure what is wrong with the function, xe4me may have the correct answer. However, I just changed my onClick to this and it worked:
onClick=\"document.f1.action='rt.php'; document.f1.submit(); return true;\"
You're using document.getElementById('f1') in submitForm function
function submitForm(action)
{
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}
But your form doesn't have id attribute because of this line of code
echo "<form method=post name='f1' action =''>";
so the form won't be submitted when you click the Careers button. You need to add id='f1' attribute to the form by changing the above line of code to below
echo "<form id='f1' method='post' name='f1' action =''>";
Try the jQuery method :
http://api.jquery.com/jquery.post/
with
How to get ID of clicked element with jQuery
Whenever any button is clicked, find its id and based on that, use $.post to post data to the location you want.
you must add a class to your button and call the onclick based on that class name :
<?Php
....
echo "<input type='submit' class='submitter' data-action='rt.php' value='Careers' >";
echo "</form>";
?>
// In Javascript :
document.getElementByClassName('submitter').onclick = function(){
var action = this.data('action');
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}

PHP Page load/refresh to exact position

What I'm trying to do is to pass a user to a php script via a href link, then have them passed back to exactly the same position that they were at before they clicked the link, like the page hasn't been refreshed. Does anyone know if or how this could be possible possible? Thank you.
Using HTML you can have the following
<p id='open_here'><a href='script.php'> Send to script </a> </p>
And then you can link back to that exact position with
Send Back to page
So essentially, instead of using a regular link as in the previuos code snippet, you could redirect back to the page using
//php redirect
<?php header('Location: mypage.html#open_here'); ?>
//Javascript redirect
<script type='text/javascript'>
window.location = "mypage.html#open_here";
</script>
If you don't mind adding some Javascript to make it work, here is a solution that will make it possible to redirect back to the exact same scrollbar position as when the user clicked the link.
index.php (the file where the link is)
<script>
window.addEventListener('load', function() {
// Do we have a #scroll in the URL hash?
if(window.location.hash && /#scroll/.test(window.location.hash)) {
// Scroll to the #scroll value
window.scrollTo(0, window.location.hash.replace('#scroll=', ''));
}
// Get all <a> elements with data-remember-position attribute
var links = document.querySelectorAll('a[data-remember-position]');
if(links.length) {
// Loop through the found links
for(var i = 0; i < links.length; i++) {
// Listen for clicks
links[i].addEventListener('click', function(e) {
// Prevent normal redirection
e.preventDefault();
// Redirect manually but put the current scroll value at the end
window.location = this.href + '?scroll=' + window.scrollY;
});
}
}
});
</script>
page.php (the PHP script that redirects back)
<?php
// Get the provided scroll position if it exists, otherwise put 0
$scrollPos = (array_key_exists('scroll', $_GET)) ? $_GET['scroll'] : 0;
// Redirect back to index.php and provide the scroll position as a hash value
header('Location: index.php#scroll='.$scrollPos);
Hope it helps! :)
I am just spilling ideas here, but I would use javascript to intercept user's click on the href, and .preventDefault first. Then figure out where the user is on the page. Maybe by splitting the page into sections, indentified by IDs. Your html markup would be something like
<div id="section-1"></div>
<div id="section-2"></div>
<div id="section-3"></div>
so when javascript prevents the link from executing, it would figure out in which section the user currently is. Let's say we know each section's height. Then we need to find out the scrollbar position. I haven't done that, but have a look here
http://api.jquery.com/scrollTop/
Once we know the height of each section and once we can detect where the scroll bar is, we can determine in which section the user is residing. Then, we fetch the url of the href link and add a query string to it like, http://something.com/script.php?section=2 and redirect user to it with whatever data you want . Then once the script has done it's job append the query string to the redirect-uri and redirect the user back with something like http://something.com#section-2 and the user will immediatly pop to section-2
I know this isn't a very specific answer, but hopefully I've given you some leads and ideas how to accomplish this. Let me know how it works!
I'd had to remember the scroll position for a <select>. Example below. Three
submit buttons to illustrate why there's three getElementById. To see
it work you must move the scroll bar first
<?php
$scrollusObscura=$_GET["imgbtn"];
$header = <<<EOD
<!DOCTYPE html>
<html>
<head>
<title>snk_db</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<head>
<script>
function gety(){
var y=document.getElementById('myUlID').scrollTop;
document.getElementById('imgbtn1').value=y;
document.getElementById('imgbtn2').value=y;
document.getElementById('imgbtn3').value=y;
}
function itemRelevatur(scrollum){
document.getElementById('myUlID').scrollTo(0, scrollum);
}
</script>
</head>
<body onload="itemRelevatur({$scrollusObscura})" >
EOD;
$html= <<<EOD
<div >
<select size="6" id="myUlID" name="myUlName" onscroll="myTimer = setInterval(gety, 300)">
<option>'1'</option>
<option>'2'</option>
<option>'3'</option>
<option>'4'</option>
<option>'5'</option>
<option>'6'</option>
<option>'7'</option>
<option>'8'</option>
<option>'9'</option>
<option>'10'</option>
<option>'11'</option>
<option>'12'</option>
<option>'13'</option>
<option>'14'</option>
<option>'15'</option>
<option>'16'</option>
<option>'17'</option>
<option>'18'</option>
<option>'19'</option>
</select>
</div>
EOD;
$html1= <<<EOD
<div><form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn1' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html2= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn2' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html3= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn3' value=''></input>
<input type='submit' value='Submit' ></input>
</form></div>
EOD;
echo $header;
echo $html;
echo $html1;
echo $html2;
echo $html3."</body></html>";
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>

how to pass POST variable by links to own pages?

Hi i wannna get variable $_POST by link to self pages. Example :
<?PHP
$var = 'PIG';
echo "<a href='test.php?var=$var'>link</a>";
if (isset($_POST['var']))
{
echo $_POST['var']);
}
?>
it links to own pages. (test.php)
It not works, who can help me please. Thanks
A link cannot POST data, only GET.
In contrast to the GET request method where only a URL and headers are
sent to the server, POST requests also include a message body. This
allows for arbitrary length data of any type to be sent to the server.
Basically, a POST requires two requests, 1) the server receives the "normal" request, with an extra header value indicating that more data needs to be sent. At that point, the server sends an acknowledge and 2) the client sends the POST body. This behavior cannot be achieved only with a link.
However, there are solutions to this and I have seen some technique, among others, outputting a form with an autosubmit, something like
<form name="frm" method="post" action="http://your.domain.com/path/to/page.php?param1=1&param2=2">
<input type="hidden" name="foo" value="bar" />
</form>
<script type="text/javascript">
document.forms["frm"].submit();
</script>
which would result into calling page.php with these arguments
$_GET = array('param1' => '1', 'param2' => '2');
$_POST = array('foo' => 'bar');
Note that this is a simple "redirect" method, but you can create <a> elements to actually trigger some hidden form like that instead of using the standard link. (untested code)
A simple link
<script type="text/javascript">
function dopost(url, params) {
var pe = '';
for (var param : params) {
pe += '<input type="hidden" name="'+param+'" value="'+params[param]+'" />';
}
var frmName = "frm" + new Date().getTime();
var form = '<form name="'+frmName+'" method="post" action="'+url'">'+pe+'</form>';
var wrapper = document.createElement("div");
wrapper.innerHTML = form;
document.body.appendChild(wrapper);
document.forms[frmName].submit();
}
</script>
This is probably what you need, actually.
Items in the query string are available via $_GET, not $_POST, since they are not actually POSTed. If you want to POST then you must either use a form with a method of post, or you must perform a XHR as POST.
Unfortunately, you really can't do that. If you need to use an anchor to submit a value, then you will need to access the variables through $_GET or $_REQUEST.
If it has to be a $_POST (if you are set in that design decision, because $_GET actually makes a lot more sense there), you can use a form and the style the submit button to make it look very much like a link. Put this code in a text editor and check it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
.button {border:none;background-color:#FFFFFF}
.button:hover{ color:blue; }
</style>
</head>
<body>
<form action="test.php">
<input type="hidden" name="var" value="<?php echo $val; ?>" />
This kinda looks like a link:
<input type="submit" value="link" class="button" />
</form>
</body>
</html>
If you have multiple links and you don't want to rewrite all of them, just add one fake form like this:
<form id="fakeForm" method="post">
<input type="hidden" name="post_key" value="post_value" />
</form>
and set up proper jquery:
$('a').click(function(event){
event.preventDefault();
$('#fakeForm').attr('action',$(this).attr('href')).submit();
});
In this case, when you click on any link, the landing page receives the post_value variable.
Note that if the link is clicked with other than left click (or js is disabled), the link works properly, but the value isn't passed!
This code below demonstrates T30's idea works.
My rationale for passing via $_POST is to prevent certain variables from being exposed in the url which is accomplished here. However, they would still be exposed via "view source".
<?php
/*
This demonstrates how to set $_POST from a link in .php without ajax based on the idea from http://stackoverflow.com/a/27621672/1827488. The rationale for doing so is to prevent certain variables ('userid') from being exposed in the url via $_GET. However, there does not seem to be a way to avoid those variables being exposed by 'view source'.
*/
echo "<!DOCTYPE html><html lang='en'><head><title>Test Data Link</title></head><body>";
// only one hidden form
echo "<form class='hiddenForm' method='post'>
<input class='hiddenFormUserid' type='hidden' name='userid'/>
</form>";
// as many links as you need
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=101>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=101>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=102>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=102>Followers</a></p>";
echo "<p><a class='hiddenFormLink' href='?following=1' data-userid=103>Following</a> • <a class='hiddenFormLink' href='?followers=1' data-userid=103>Followers</a></p>";
echo "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>";
echo "<script type='text/javascript'>
console.log('jq');
$('.hiddenFormLink').click(function(e){
console.log('data-userid=' + $(this).attr('data-userid') + ', value=' + $('.hiddenFormUserid').val());
e.preventDefault();
$('.hiddenFormUserid')
.val($(this).attr('data-userid'));
$('.hiddenForm')
.attr('action',$(this).attr('href'))
.submit();
});
</script>";
if (isset($_GET["following"]) || isset($_GET["followers"])) {
if (isset($_GET["following"])) {
echo "followed by ";
} else {
echo "followers of ";
}
if (isset($_POST["userid"])) {
echo $_POST["userid"]."<br>";
} else {
echo "no post<br>";
}
} else {
echo "no get<br>";
}
echo "</body></html>";
$_POST["userid"] = "";
?>

Categories