jQuery - Pass variable to php - php

I'm very new to this and I've searched around all day today to get it working but I haven't managed to find a way to use a variable, only hard-coded values work. Here is my code with a hard-coded value:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "845" } );
}
);
</script>
What I'd like to have is change that 845 value to a variable called $vpostid. When I change it to that it doesn't work, so I assume I need to get the double quotation marks around the number but I can't see to get the correct combination.

I'm assuming you mean "pass variable from php":
If short hand openings are enabled:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?=$vpostid?>" } );
}
);
</script>
else:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?php echo $vpostid; ?>" } );
}
);
</script>

try this code:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?php echo($vpostid); ?>" } );
}
);
</script>

Related

How to send values of Select button from Mysqli database and send to second pages?

I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.

How to properly echo PHP variables within JS script?

I have this script that needs to print and it is within a PHP file as I need to pass it options because I am using the jQuery UI Tabs plugin.
Here is what I have:
<?php
$collapsible = "true";
$active = "2";
$options = array( 'collapsible' => $collapsible, 'active' => $active );
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : <?php echo $options["collapsible"]; ?>,
active : <?php echo $options["active"]; ?>
});
});
</script>
Ok so everything works however the two options collapsible and active isn't effecting it. But if I bypass the php variables and just hardcode the option settings in for collapsible and active, then it works. So I am not sure why the variables have no effect. I've even tried type casting it with (int) for active and (bool) for collapsible but still no dice.
Thanks for looking.
Rather than adding quotes, run the value through json_encode. This will ensure proper escaping as well:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : <?php echo json_encode($options["collapsible"]) ?>,
active : <?php echo json_encode($options["active"]) ?>'
});
});
</script>
It also gives you the added benefit of being able to use literal types as opposed to all strings in your PHP:
<?php
$collapsible = true;
$active = 2;
And, per axel.michel suggestion in comments, could be simplified to:
<?php
$options = array('collapsible' => true, 'active' => 2);
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs(<?php echo json_encode($options); ?>);
});
</script>
Try adding quotes around the values and encode the output
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : '<?php echo $options["collapsible"] ); ?>',
active : '<?php echo $options["active"] ); ?>'
});
});
</script>

How do I pass the value of a PHP variable to Javascript code?

I need help with putting this $id value into the javascript below
PHP:
<?php
$id = NULL;
$username = 'YouTube';
$xml = simplexml_load_file(sprintf('http://gdata.youtube.com/feeds/base/users/%s/uploads?alt=rss&v=2&orderby=published', $username));
if ( ! empty($xml->channel->item[0]->link) )
{
parse_str(parse_url($xml->channel->item[0]->link, PHP_URL_QUERY), $url_query);
if ( ! empty($url_query['v']) )
$id = $url_query['v'];
}
echo $id; // Outputs the video ID.
?>
JS: Need $id value ---> 'I need the value to go right here'
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: 'I need the value to go right here', start: 3 };
$('#video1').tubular(options);
});
</script>
Do something like this....
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: '<?php echo $id?>', start: 3 };
$('#video1').tubular(options);
});
</script>
But make sure, you are including this script in php file.
Other solution could be to use html hidden variable, and access that value using js.
by the use of
<script type="text/javascript">
....
</script>
I understand you're using javascript inside of your view! then why not just do this
var options = { videoId: '<?php echo $id; ?>', start: 3 };
Use
<script type="text/javascript">
var id= '<?= $id; ?>';
</script>
now you can use the id variable in your javascript
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: id, start: 3 }; // id variable which is filled by $ib variable of php
$('#video1').tubular(options);
});
</script>

javascript code is not being executed

I am working on this project in which I am trying to get a returned value so I can autofill my input boxes according to what the client selects.
This code however is not executing and I do not know why. When I remove the src="jquery area" $(#dropdown).on is an undefined method; not to sure what to do.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
Here's my full code
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//$DBH->prepare('SELECT first FROM contacts');
}
catch(PDOException $e) {
echo "I'm sorry, I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
//get query
$FNresult=$DBH->query('SELECT first FROM contacts');
//set fetch mode
$FNresult->setFetchMode(PDO::FETCH_ASSOC);
$dropdown = "<select name='contacts' id='contacts' >";
while($row =$FNresult->fetch()) {
$dropdown .= "\r\n<option value='{$row['first']}'>{$row['first']}</option>";
// echo getLN();
}
$dropdown .= "\r\n</select>";
echo $dropdown;
//}
/*
// Get last name
function getLN(){
$query = "SELECT last FROM contacts";
$LNresult=mysql_query($query);
$last;
while($row = mysql_fetch_assoc($LNresult)) {
$last = "{$row['last']}";
}
echo $last;
}//end getLN
*/
$DBH = null;
?>
<!-- javascript on client-side -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
//$.post(url, [data], [callback], [callback type])
("#dropdown").on('change', function() {//when you select something from the dropdown function run and will switch the data
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
/*("#dropdown").on('connection', function (stream) {
console.log('Ah, we have our first user!');
});*/</script>
<form action="insert.php" method="post">
First Name: <input type="text" id="first" name="first"><br>
Last Name: <input type="text" id="last"><br>
Phone: <input type="text" id="phone"><br>
Mobile: <input type="text" id="mobile"><br>
Fax: <input type="text" id="fax"><br>
E-mail: <input type="text" id="email"><br>
Web: <input type="text" id="web"><br>
<input type="Submit">
</form>
here is my new edited script on output page =
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$("#contacts").on('change','#dropdown', function() {
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
</script>
here is the php file for backgroundScript.php =
<?
// background script
// retrieve data based on $_POST variable, set to $returnArray
$returnArray = $_POST[array(
'first' => firstName,
'last' => lastName,
)];
/****************************
* the structure of returnArray should look something like
array(
'first' => firstName,
'last' => lastName,
)*/
echo json_encode($returnArray);
?>
this file will send in info so the javascript will then replace form fields with what ever is held in the areas appointed
It would appear that your PHP script is returning some formatted html, which you then try to insert into the dom via .val(). That method is used to set the values of form fields, not insert entire chunks of html. Try using .append() or .html() instead, plus do what Phil suggested above - split your script into multiple blocks.
You need to include your jQuery prior to using it:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// Your Code Here
</script>
Better yet would be to use external JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="js/site.js"></script>
And if you're using HTML5 the type="text/javascript" isn't even needed so:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/site.js"></script>
Even better still would be to use a jQuery CDN:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/site.js"></script>
Also, as others have noted, be sure to use $ at the beginning of your jQuery factories. i.e. $('#dropdown')
-- Update --
Further clarification on project tree, most basic project trees look like this:
root/
|--css/
|--images/
|--js/
|--site.js
|--index.html
-- Update 2 --
Example of a $.post
$.post({
'somescript.php', // Script your posting to
{
someParam1: someData1, // $_POST['someParam1']
someParam2: someData2
// etc etc
},
function(response){
// Do something with JSON response upon successful post
alert(response);
},
'json' // Tells the script that JSON will be returned
});
-- Update 3 --
Okay so basically you want to do is...
Javascript:
var dropdown = $('#dropdown');
dropdown.bind('change', function(){
$post.(
'backgroundScript.php',
{
first: dropdown.val()
},
function(response) {
$('#first').val(response.first);
$('#last').val(response.last);
// Repeat for all of your form fields
},
'json'
);
});
Receive POST param:
$firstName = $_POST['first'];
MySQL query would be something like the following:
$sth = $dbh->prepare('SELECT *
FROM contacts
WHERE first = :first');
$sth->bindParam(':first', $first, PDO::PARAM_STR);
$sth->execute();
Then add all of your MySQL fields into associative array array(key => value) and then json_encode and return array.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$("#dropdown-parent").on('change','#dropdown', function() { // replace dropdown-parent
$.post("backgroundScript.php", {
uid: $(this).val()
},
function(data) {
$("#first").val(data.first);
$("#last").val(data.last);
// etc.;
}, 'json'
);
});
<script>
In your PHP you should have something like this
echo json_encode(array('first' => $some_value, 'last' => "Other value"));
Shouldn't
("#dropdown").on('change', function() {
be
$("#contacts").on('change', function() {

JQuery Updating Status

I am writing some jquery to call an ajax script every 2 seconds to get the result and update the page. I am mostly a backend programmer and could use some help on this.
This is the code I have now:
<script language="javascript">
function downloadProgress(id) {
$("#" + id + "").load("index.php?_controller=download&_action=getDownloadProgressAjax",
{
downloadId: id
}
);
setTimeout(downloadProgress(id), 2000);
}
</script>
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>">
<script language="javascript">
downloadProgress(<?php echo $dl["download_id"]; ?>);
</script>
</div>
<?php
}
?>
This does not work. What am I doing wrong or would you suggest another approach?
Thanks
I think that you are confusing your PHP script by giving it both query string variables (sent as GET) and data (which is probably getting sent as POST). Try this:
$("#" + id).load("index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id }
since you are using jquery, you can use the $.ajax function when the page is ready.
$(function () {
function function downloadProgress(id) {
$.ajax({
url: "index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id
})
setTimeout(function () {
if (downloadnotcomplete){ // this way your script stops at some pont.
downloadProgress(id);
}
},2000);
}
});
You will attach the downloadProgress(id) function to your download button or anything else, to trigger the function the first time.
The problem you are having is that you have to provide a parameterless function and not a function call to setTimeout. Also, I would do it a little bit different and use setInterval instead of setTimeout as it relays your intention better in the code. Here is how I would do it:
<script language="javascript">
$(function() {
setInterval(downloadHandler, 2000);
});
function downloadHandler() {
// I'm not sure where the id is coming from you will probably need to put a
// class on your div's so that you can select them.
$(".MyDivClass").each(function() {
var id = $(this).attr("id");
downloadProgress(id);
});
}
function downloadProgress(id) {
$("#" + id + "").load(
"index.php?_controller=download&_action=getDownloadProgressAjax",
{ downloadId: id }
);
</script>
and then on your div:
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>" class="MyDivClass"/>
<?php
}
?>
Hope this helps.

Categories