How to pass a php variable in window.open function - javascript

I have PHP loop ( WHILE{} ) that loops an array from MySQL and creates a page with the data line by line. I need to add to each line a button that will trigger a new page but I need to carry the value of the id of the line to that new pop-up page. This is the code I have, but i can't figure out how to pass my id to the pop up:
I know I can't add my PHP variable to the URL in the JS function, because it sits outside the loop. Can I use the JS function to add it ? Here is some simplified code:
PHP Code
<?php
while ($all = mysql_fetch_array($get_all)){
$id= $all['id'];
echo '<button type='button' class='btn btn-danger' onclick='openWin()'> Click here</button> ';
}
?>
Javascript
<script>
var myWindow;
function openWin() {
myWindow = window.open("http://www.website.com/pop.php", "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>
I need to get $id to the new page. As stated I was hoping to add it to the URL as a $_GET variable, but I don't seem to know how to add it since the url sits in the JS function outside the while loop.
Sorry for the poor indenting

just pass a parameter
while ($all = mysql_fetch_array($get_all)){
$id= $all['id'];
echo '<button type="button" class="btn btn-danger" onclick="openWin(\''.$id.'\')"> Click
here</button> ';
}
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?p_id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>

hope it will work for you.
while ($all = mysql_fetch_array($get_all)){
...
$id= $all['id'];
echo "<button type='button' class='btn btn-danger' onclick='openWin($id)'> Click here</button>";
...
}
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>

Add the id as an attribute of your HTML <button> element and pass that to the openWin function, eg
while ($all = mysql_fetch_array($get_all)) : ?>
<button type="button" class="btn btn-danger" onclick="openWin(this.dataset.id)"
data-id="<?= htmlspecialchars($all['id']) ?>">
Click here
</button>
<?php endwhile ?>
and in your JS
function openWin(id) {
myWindow = window.open(
`http://www.website.com/pop.php?id=${encodeURIComponent(id)}`,
'myWindow',
'width=600,height=800'
)
}
I've used an HTML attribute to store the value (as opposed to just injecting it into the onclick expression) to avoid the issue of having to simultaneously HTML and JS encode the value.
I've also used data-id instead of just id because a 3-digit number makes a bad HTML element ID, prone to easy conflicts.

2 steps to follow
Pass your php variable $id to javascript function using function-call-by-value reference,
then use that argument in GET request for url to be opened in new window
$id= $all['id'];
echo "<button type='button' class='btn btn-danger' onclick='openWin(".$id.")'> Click here</button> ";
}
?>
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>

Use cookies or HTML5 localStorage if its purely on the client-side.
Simple jQuery (Pass as a query string in the URL)
<script>
var myWindow;
function openWin(id) {
myWindow = window.open("http://www.website.com/pop.php?p_id="+id, "myWindow", "width=600,height=800");
}
function closeWin() {
myWindow.close();
}
</script>
Example 2 Simple jQuery (Pass as a query string in the URL via function)
function set_url_data(go_to_url, data) {
new_url = go_to_url + '?data=' + data;
window.location.href = new_url;
}
LocalStorage
//Set data
localStorage.setItem('bookedStatus' + customerId, true);
//Get data
localStorage.getItem('bookedStatus');
Ajax
<script>
$.ajax({
type: "POST",
url: package.php,
data: $("#myform").serialize(),
success: function(data)
{
$('#Result').html(data);
}
});
</script>

Related

Ajax not calling PHP

I have a problem with ajax calling a PHP code without change current page. In the php_error.log there is no reference to the PHP file. I have no errors on screen or anything to guide me to resolve the problem.
This is my javascript function
<script type="text/javascript">
function getMail(){
var name = $('#username').val();
var dominio = $('#dominio').val();
if(name.trim() == '' ){
alert('Ingrese su nombre de usuario.');
$('#username').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'paginas/recover.php',
//data:'username='+name+'&dominio='+dominio,
beforeSend: function () {
$('.nextBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
$('#username').val('');
$('.nextBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
},
});
}
};
</script>
This is the function calling button from the HTML
<button id="nextBtn" type="button" class="btn btn-primary nextBtn btn-lg pull-right" onclick="getMail()" disabled>Continuar</button>
And this is the PHP code
<?php
//include ('../paginas/header.php');
include ('../paginas/funciones.php');
//$dominio = $_GET['dominio'];
//$usr = $_GET['username'];
//getToken($usr,$dominio);
$to_mail = 'mail#gmail.com';//getMail($usr, $dominio);
$to_name = 'Usuario Prueba';
$message = 'Prueba';
$subject = 'Prueba';
sendMail($to_mail,$to_name,$subject,$message);
?>
If I access the PHP file alone, the mail was sent, but when I use the javascript function, nothing happened. The function was invoked because if I don't complete the username in the form the alert was executed.
Thanks
//data:'username='+name+'&dominio='+dominio,
change above line to this make it uncomment and pass data as blank
data:'',

Ajax Call in Javascript Function On Button Click

I am getting an error in this code which says Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick.I cannot figure out where i am going wrong.
Here is my code which contains a while loop which fetches data from the database and $xyz goes to the javascript function called myFunction().
Here is my file:
if($rs->num_rows>0)
{
while($row=$rs->fetch_object())
{
$xyz=$row->judged_id;
$my="SELECT DISTINCT first_name,picture from user1 where id='$xyz'";
$hj=$con->query($my);
if($hj->num_rows>0)
{
while($rz=$hj->fetch_object())
{
echo $name=$rz->first_name;
$pic=$rz->picture;
echo"<img src='$pic' height=100 width=100>";
?>
<button type='button' class='egf' onClick="myFunction('xyz')">Chat</button>
<br><br>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var xyz=<?php echo $xyz; ?>;
function myFunction('xyz')
{
$.ajax({
type: 'GET',
url: 'chat/public/01_index.php?id2=xyz',
success: function(data) {
$('.chat-list').html(data);
}
});
});
}
</script>
<?php
}
}
What is the content of the PHP variable $xyz? If it is a string, for example,
this:
var xyz=<?php echo $xyz; ?>;
Would result in a JavaScript like:
var xyz=ABCDEFG;
Which is not valid. Instead it should then be:
var xyz = '<?php echo $xyz; ?>';
Furthermore your function defintion seems not right, should be something like this instead, since you can not specify a string as a parameter name:
function myFunction(varNameHere)
{
alert(varNameHere);
}
Click me
Also you are using jQuery ready() function inside your function, which will probably not fire at anytime.
I think what you are looking for is something like this:
function myFunction(xyz)
{
$.ajax({
type: 'GET',
url: 'https://httpbin.org/get?q=' + xyz,
success: function(data) {
$('.chat-list').html(data.args.q);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
<div class="chat-list">
</div>
First of all: you don 't need jQuery. The jQuery library is just a wrapper written in native javascript. It would be more performant to use native javascript.
After that as I mentioned in the comments, you should use a click event listener on the parent element, which contains all your buttons. Just have a look at the following example.
<div class="parent-element">
<?php
while ($row = $resource->fetch_object())
{
echo '<button id="' . $row->id . '">' . $row->title . '</button>;
}
?>
</div>
<script>
var parent = document.querySelector('.parent-element'),
xhr = new XMLHttpRequest();
parent.addEventListener('click', function( event ) {
let target = event.target;
if (target.tagName.toLower() == 'button' && target.id) {
// your xml http request goes here
xhr.open('GET', yoururl + target.id);
xhr.onload(function() {
if (xhr.status === 200) {
// do something with the response
let response = xhr.responseText;
}
});
xhr.send();
}
}, true);
</script>
The while loop adds the buttons to your HTML markup. Further a click event listener was added to the parent div element. On every click it checks, if the target element is a button and if this button has an id attribute. If so an asynchronous request is executed.

How do I execute a php switch case with ajax onclick and have it print the result in an H tag?

I have a page called beslutning.php with a random generator first followed by a switch case.
That page is included in the index file like so:
<h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" ?></h1>
On a page load it runs the script, match a case and echoes out the result as it's intended.
Here's what I need
A button on the index page which when clicked requests the beslutning.php to be run again so I get a new result.
All my searches on phrases such as execute php script with ajax, run a php script with ajax onclick and a bunch of other alternatives has lead me to no result.
I have tried to fiddle with blocks of codes like the one below but to no luck.
<script>
$(document).ready(function(){
$("#NyBeslutning").click(function() {
$.ajax({
type: "POST",
url: "beslutning.php", //Your required php page
data: "$beslutning", //pass your required data here
success: function(response){
$('$beslutning').html(response);
}
});
return false;
});
</script>
<a id="NyBeslutning" class="btn btn-lg btn-default" type="button" onClick="$beslutning()">Ny beslutning</a>
Here's how my beslutning.php looks like:
<?php
$beslutning = mt_rand(0, 1000);
switch($beslutning)
{
case 1:
echo "something";
break;
case 2:
echo "something";
break;
?>
Someone who can help?
Explain it to me like I'm a baby :)
Thanks in advance.
You're close, but you have some big problems with your jQuery code. Try to read up on documentation for these things before using them!
You aren't sending any data, so don't need to POST and can just do a simple GET request. In your success function you were referring to $('$beslutning') which isn't anything. Instead you want to refer to your H1 element. And, you'd forgotten closing braces around some code.
On the HTML side, you don't need an onclick attribute, since you're already declaring the click listener in the script. Give this a try, and if it doesn't work, check your browser's error console.
<script>
$(document).ready(function(){
$("#NyBeslutning").click(function() {
$.get("beslutning.php", function(response) {
$('h1.cover-heading').html(response);
});
});
});
</script>
<h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" ?></h1>
<button id="NyBeslutning" class="btn btn-lg btn-default">Ny beslutning</button>
You must run onto virtual server (laragon etc.).
localhost/index.php <
PHP as select
file: index.php
<form class="selected">
<select name="category" id="categories">
<option value="">vyberte si...</option>
<option value="cuba">Rum</option>
<option value="cola">Cola</option>
<option value="saris">Beer</option>
<option value="moto">Oil</option>
<option value="barique">Wine</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="app.js"></script>
PHP Switch Case
file: ajax.php
<?php
$category = $_POST['category'];
switch ($category) {
case "cuba":
print "You must read Dickens.";
break;
case "cola":
print "Don't touche me!";
break;
case "moto":
print "You will not move without me.";
break;
default:
print "Great, relax it.";
}
?>
jQuery AJAX:
file: app.js
(function($){
var comment = $('<div/>', { id: 'comment' }); // create new element
var categories = $('#categories');
comment.appendTo( $('.selected') );
categories.change( function() {
var req = $.ajax({
url: 'ajax.php',
type: 'POST',
data: categories.serialize()
});
req.done( function(data){
//console.log( data);
comment.text( data );
})
});
})(jQuery);
You can just pass a parameter when you click something in the index.php
<button onmousedown=someFunction()>Click ME</button>
<script>
someFunction(){
set href value here based on your condition example one,two, three
window.location = localhost/main.php?switchVariable = one;
}
</script>
in main.php
<h1 class="cover-heading">Vores beslutning: <?php include "beslutning.php" </h1>
write
in beslutning.php file write this
<?php
$beslutning= $_GET['switchVariable '];
switch($beslutning)
{
case one:
echo something;
break;
case two:
echo something;
break;
?>

Posting Javascript variable to PHP document

I want to get the value of data-id in my tag and transfer it to a PHP variable.
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
I already got the value of data-id using the javascript below and placed it into a variable, however its not posting on the page.
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid});
});
I tried doing this...
print_r($_POST);
but the array being displayed is empty What am I doing wrong here? Kinda new at this.
If you're trying to post on the same page (which is a bad idea anyway), you should have always have an exit/die; on that PHP catch block, and a success function callback on the $.post.
Example:
Simulated JS:
<?php $adminid = 1; ?>
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid}, function(response){
console.log(response);
});
});
</script>
Here on the PHP (same page):
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
}
Or
if(isset($_POST['admin_to_pass'])) {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
// you must have this or you'll catch the whole document
}
And since in your current code you don't have one, you need the success callback function to process the response which came from the server:
$.post("index.php", {admin_to_pass: adminid}, function(response){
^^^^
console.log(response); // your response from the server is inside (you can name it any name you want)
});

JQuery Functions loading prematurely

What my aim here is when a button is pressed, it replaces the content of the div with a textbox and a button. And when the button is pressed, it posts the text to a script, which handles the request and stores the inputted data from the textbox into the database.
It is then set to call another function called Reset(); which is supposed to restore the old contents of the div. However, the idea that I had in mind it calls the DB Query to find what's CURRENTLY in the database. But, it's not doing that, it's just getting the old value. Which makes me think that the function is running at the start of the page, and not when it is called.
It definitely updates the value because when I refresh the value is updated. Here's my code:
<script>
$(function () {
$('#button').on('click', function(e) {
var myVar = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<div class='span12'><h2>Revision Notes</h2><form id='revisionnotes' name='revisionnotes' method='POST'><textarea style='width:100%;height:290px; padding:10px;' id='notes' name='notes'>" + myVar + "</textarea><br/><button onclick='Button();' name='submit' id='submit' class='btn btn-primary'>Change Revision</button></div></form></div>");
});
});
function Reset() {
var myVar2 = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<h2>What's new?</h2><div class='well'>" + myVar2 + "</div><input type='button' value='Change Revision' id='button' name='button' class='btn btn-primary'>");
});
function Button() {
$('#revisionnotes').on('submit', function(e) {
var data = $(this).serialize();
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: data, // $('form').serialize(),
success: function (data, textStatus, jqXHR) {
Reset();
alert("Delta - POST submission succeeded");
}
});
e.preventDefault();
});
}
</script>
Is there any way to stop the function from retrieving the value from the database until it is called from the Success of the Button function?
Many thanks, Jarrod.
$(function () {
$('#button').on('click', function(e) {
var myVar = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<div class='span12'><h2>Revision Notes</h2><form id='revisionnotes' name='revisionnotes' method='POST'><textarea style='width:100%;height:290px; padding:10px;' id='notes' name='notes'>" + myVar + "</textarea><br/><button onclick='Button();' name='submit' id='submit' class='btn btn-primary'>Change Revision</button></div></form></div>");
});
});
this is not "exactly" a function, it is a closure around a piece of code that runs only once, onload of page.
If u want to load a changing value from your server, you would need to use AJAX, same as u use for the data submission.

Categories

Resources