I have like:
<script type="text/javascript">
$(document).ready(function() {
var n = $('<?php echo $_GET['name'];?>').val();
var e = $('<?php echo $_GET['email'];?>').val();
$.ajax({
method: "POST",
url: "file.php",
data: {name: n, email: e},
success: function(status) {
$('#result').append(status);
}
});
});
</script>
Why does it store empty values inside e and n?
And inside file.php when I echo em they are empty.
But here when I echo $_GET['name'] or email it show real values?
Thanks
you have a mistake in your code. you have to store that variable like below.
var n = '<?php echo $_GET['name'];?>';
var e = '<?php echo $_GET['email'];?>';
Why does it store empty values inside e and n?
My guess is that jQuery isn't finding the matching elements you're looking for. For example, if I go to your page with this:
page.php?name=David
Then that code will emit this:
var n = $('David').val();
That jQuery selector would be looking for this:
<David />
Which probably doesn't exist on that page. (With an email address it would be even stranger.)
If you want to store the values themselves in a JavaScript variable, you don't need any jQuery for that:
var n = '<?php echo $_GET['name'];?>';
If, on the other hand, the $_GET['name'] value is supposed to be the name of the HTML input and you want to use jQuery to find that input, it would be more like this:
var n = $('input[name=<?php echo $_GET['name'];?>]').val();
It's not entirely clear if that's what you're looking to do, though. Depends on what you expect $_GET['name'] to contain.
You can confirm all of this using the debugging tools in your browser. (Usually opened by pressing F12.) Examine the page source client-side (after the PHP code has been processed) to see what your JavaScript is actually doing, look at the jQuery selector(s) you're trying to build, debug the JavaScript to see if the target elements are found, etc.
Related
I have a php file which uses a script within it.
I'm trying to get an image called by php (the_main_image) and prepend a set of links with this image (along with a favicon which is currently working fine) using jQuery. Here's what I have so far but it currently breaks the function
<script>
jQuery(document).ready(function($) {
$("#lesen").click(function() {
var bla = $('#my_hidden_input').val();
var test = "<?php the_main_image(); ?>";
$.ajax({
url: bla,
dataType: "text",
success: function(data) {
$(".text").html(data);
$(".text a[href^='http']").each(function() {
$(this).prepend(test);
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');
});
}
});
});
});
</script>
How can I use jQuery var values that contain php within a prepend or other similar jQuery functions?
Hi I have done similar thing in my project, below worked for me.
Since you cannot write php directly in JavaScript, you need take help of your html.
Create a hidden input field in you html like below
<input type="hidden" id="something" value="<?php the_main_image(); ?>"/>
Then read this in jquery like
<script>
jQuery(document).ready(function($) {
$("#lesen").click(function() {
var bla = $('#my_hidden_input').val();
var test = $("#something").val();
$.ajax({
url: bla,
dataType: "text",
success: function(data) {
$(".text").html(data);
$(".text a[href^='http']").each(function() {
$(this).prepend(test);
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');
});
}
});
});
});
</script>
hope this helps.
If your function in php does not echo result. Try to add echo. <?php echo the_main_image(); ?>. Seems like you forgot to echo result.
P.S. You can render results from php, even use it inside js code that placed in php files, but you should remember that mixin php with js is bad practice, and should be done cautiously.
How it works: php interpreter read your file before send static html to user and interpret all php related cod inside <?php ?>, if you echoing something it will appears in that row where you do this (or call function than do echoing). As mentioned by somebody if you echoing string with quotes it can break the js if you inline your php tags inside the same type of quotes.
Try to use ajax to get php value in jquery funcion.
I have the following AJAX code, which replaces anything with class "percentreplacer" with the data in the "Percent" column of the MYSQL database:
<script type='text/javascript'>
$(document).ready(function () {
$('#functionsquestionform2').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : "aplaygroundajaxtest.php",
type: "POST",
data: $(this).serialize(),
success: function (data) {
$(".percentreplace").text(data.percent);
},
});
});
});
</script>
In another part of my script, I have this snippet of PHP code:
<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>
When I run the code, the AJAX code at the top successfully replaces the above span with the percent value stored in the database (such as "6").
Later on in my code, I try to set this percent as a variable with the JQuery script shown below:
<script type='text/javascript'>
$(function(){
var carouselbutton1percentage='<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>' ....[cont'd]
Here, however, instead of replacing the entire PHP snippet with the percent (let's say 6), it sets the variable carouselbutton1percentage equal to <span class="percentreplace">6</span> I want the tags to get stripped here just like they did in the former. I'm guessing this has something to do with the quotes, but I've played around with it quite a bit and I can't figure out what to change.
Any help would be greatly appreciated!
Thanks
I might be missing something. But instead of storing a string 'that contains characters that look like PHP and jquery', I would think you want to actually update that html element, like you do in the AJAX response block. So..
$(".percentreplace").text('6');
or
var carouselbutton1percentage = 6;
$(".percentreplace").text(carouselbutton1percentage);
But again, maybe I'm misunderstanding.
I think you need to escape your string properly?
var carouselbutton1percentage='<?php echo \'<span class="percentreplace">\'.$data[\'FunctionsPercent\'].\'</span>\'; ?>';
I have 2 js files and i want to pass 2 variables from file1.js to file2.js. What i have done until now is to send these 2 variables from file1.js in a 3rd file file3.php with ajax using this:
$('#replace').click(function(){
var replacement = cur;
var replacement2 = cur2;
$.ajax({
url: DOMAIN_NAME+"file3.php",
type: "post",
data: {replacement: replacement, replacement2 : replacement2},
success:function(data){
console.log(data);
},
error:function(){
alert('Something Went Wrong');
},
});
});
In my file3.php:
if(isset($_POST['replacement']) && isset($_POST['replacement2']){
$a = $_POST['replacement'];
$b = $_POST['replacement2'];
}
<input type="hidden" id="af" value="<?=$a;?>">
<input type="hidden" id="bf" value="<?=$b;?>">
In my File2.js:
var a = $('#af').val();
var b = $('#bf').val();
i can see that in the network the ajax passes the variable with a status 200 OK but in the php file my variables doesn't pass. So the file2.js can't get the values. What i am doing wrong??
Let's say you have this simple form:
<form id="my_form">
<input type="text" name="a_field" id="a_field">
<input type="text" name="b_field" id="b_field">
<button id="submit_form">Submit</button>
</form>
The jquery script file (#1) for this form can be named "script1.js" and can look like that:
$(document).ready(function(){
$('#submit_form').on('click').function(e){
e.preventDefault();
var formData = $('#my_form').serialize();
$.ajax({
type: 'POST',
url: 'my_ajax.php',
data: formData
});
});
});
Notice that I serialized the form to be quicker... (If you want you can specify which variables you want to pass to ajax)
Here is an example of my_ajax.php:
<?php
session_start();
if(isset($_SESSION["a_var"])){unset($_SESSION["a_var"]);}
if(isset($_SESSION["b_var"])){unset($_SESSION["b_var"]);}
if(isset($_POST["a_field"])){$a_field=htmlspecialchars($_POST["a_field"]);}else{$a_field=""; exit();}
if(isset($_POST["b_field"])){$b_field=htmlspecialchars($_POST["b_field"]);}else{$b_field=""; exit();}
$_SESSION["a_var"] = $a_field;
$_SESSION["b_var"] = $b_field;
?>
With the above file, we created two php sessions based to the input-field values that we acquired from our html form.
Now the "tricky" part:
Your SECOND js file (#2) must be given an extension .php and NOT .js
It will however execute any javascript code if of course that code is enclosed in "script" tags
Let's name that file "script2.js.php" -which can be like that:
<?php
session_start();
if(isset($_SESSION["a_var"])){$value_a = $_SESSION["a_var"];}else{$value_a="";}
if(isset($_SESSION["b_var"])){$value_b = $_SESSION["b_var"];}else{$value_b="";}
?>
<script>/*...include jquery here (if necessary)...*/</script>
<script>
$(document).ready(function(){
//jquery is NOT necessary for my example
//I just included it in case you need to do other tasks...
var valueA = '<?php echo $value_a; ?>';
var valueB = '<?php echo $value_b; ?>';
//Now you can do anything with these values... For example, you could alert them:
alert('Value A: '+valueA+' - Value B: '+valueB);
});
</script>
One last thing:
While to include a js file to your html page you do:
<script src="http://www.example.com/scripts/yourscript.js"></script>
To include the "js.php" file you must do it by using the php "include" function:
This is how I would suggest to pass variables from one js file to another by using php sessions!
My example is quite "basic" and could take a lot of "polishing" work regarding functionality and security... But should give you an idea as of how to start...
Hope that helps you and/or others...
I am working on a form in which changing one "select" element modifies the values of another "select" element. The values of both the elements come from a MSSQL database. What is the best way to implement code that can accomplish this?
There are two ways that I can think to do it.
Store the table into a javascript variable and make the onchange event of the first element modify the second element.
Send a GET request to the page and reload it, using PHP to modify the second element.
I don't like the first method because storing the database from the PHP side to the javascript side seems kind of hacky and really cumbersome to do. I don't like the second way either, because reloading the page disrupts the user experience and makes him have to scroll down again.
You should use AJAX to pull in data and populate the second select element. In a nutshell, AJAX is simply a separate page request that happens behind the scenes. You can use it to load a simple HTML page or partial and display it in a DOM element, or you can use it to dynamically retrieve structured data.
The best way to do this would be using JSON (JavaScript Object Notation). In this case, you would use Javascript to make an AJAX call to a PHP page, and that PHP page would take an argument in the query string that represents the value of the first select element. With that, you would make a call to your MSSQL database to get all of the corresponding options for the second select, and then echo those out. In turn, the Javascript you use to make the AJAX request can parse the response and interpret it as a JavaScript object literal, allowing you to loop through the results and do what you want with them.
Here's an example (I'm using jQuery, since it makes AJAX really easy).
At the top of your form page:
$(document).ready(function() {
$('#select1').change(function() {
var select1val = $(this).val();
$.getJSON('/path/to/response.php', 'select1=' + select1val, function(response) {
$('#select2').empty();
if(response) {
for(var option in response) {
$('<option/>').val(option.value).html(option.label).appendTo($('#select2'));
}
}
});
});
});
And then your response.php page should look like this:
<?php
$select1 = $_GET['select1'];
// Do validation here, to make sure it's a legitimate value for select1. Never trust the
// user input directly.
// Replace this with whatever code you use to make DB queries.
$options = $mydb->query("SELECT value,label FROM select2_options WHERE select1_value=?", $select1);
echo json_encode($options);
Use Ajax if you don't want to reload the page. Read more about AJAX
$('#select1').change(function() {
var value = $(this).val();
var dataString = 'id='+ value;
if(value != '')
{
$.ajax({
type: "POST",
url: "fetchOptionsForSelect2.php",
data: dataString,
success: function(html) {
$('#select2').html(html);
}
});
}
else
{
//reset select2
$('#select2').html("<option value=''>Select value from select1 first</option>");
}
});
Here is a stand-alone example that does what you want. It might look complicated at first, but AJAX via jQuery is quite straight-forward.
This example uses two files:
1) TEST.PHP - contains the javascript/AJAX, and the HTML with the <select> controls
2) PROCESS.PHP - receives data from test.php (via AJAX), runs a MySQL lookup on that data, returns HTML back to TEST.PHP
TEST.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#workers").change(function(event) {
var w = $(this).val();
//alert('Value of w is: ' + w);
//return false;
$.ajax({
type: "POST",
url: "process.php",
data: 'worker=' + w,
success:function(data){
//alert(data);
$('#laDiv').html(data);
}
}); //END ajax
});
}); //END $(document).ready()
</script>
</head>
<body>
Worker:
<select id="workers">
<option>Roy</option>
<option>John</option>
<option>Dave</option>
</select>
<div id="laDiv"></div>
</body>
</html>
PROCESS.PHP
<?php
$w = $_POST['worker'];
$ret = '
Fruit Options:
<select id="fruitopts" name="Select2">
';
if ($w == 'Roy'){
$ret .= '
<option>Apples</option>
<option>Oranges</option>
<option>Pears</option>
';
}else if ($w == 'John') {
$ret .= '
<option>Peaches</option>
<option>Grapes</option>
<option>Melons</option>
';
}else if ($w == 'Dave') {
$ret .= '
<option>Nut</option>
<option>Jelly</option>
';
}
$ret .= '</select>';
echo $ret;
Here's what happens:
a. TEST.PHP - User selects choice from dropdown "workers"
b. change() event fires, gets value of ("w"), and sends that to process.php
c. PROCESS.PHP receives a variable key named w in its $_POST[] array, stores in $w
d. PROCESS.PHP does a MySQL lookup on the selected worker (value of $w)
e. PROCESS.PHP constructs some HTML in a var called $ret, then ECHOs it out
f. TEST.PHP receives the HTML string inside the $.ajax success function
g. TEST.PHP calls the received data data (-1 for originality)
h. TEST.PHP injects the received HTML into the DIV with id="laDiv"
Hope that helps.
Use http://www.appelsiini.net/projects/chained
<script src="jquery.chained.min.js"></script>
<select id="mark" name="mark">
<?php
foreach($select1_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
<select id="series" name="series">
<?php
foreach($select2_opt as $opt)
{
echo "<option value=$opt>$opt</option>";
}
?>
</select>
So, heres a super simple jQuery / AJAX comment system step one. Step two is the PHP to insert the data into the DB. I need the $_GET['variable'] for the page / a $_SERVER['variable'] to store into the DB. How can I get these in the jquery. I can't just say $spot = $_GET['spot'] or $url = $_SERVER['FILE_SCRIPTNAME'] in the PHP. It won't pick it up. I has to be sent through the jQuery / AJAX. How can I do this?
$(document).ready(function() {
$('#submit_comment').click(function() {
var comment = $('#place_comment').val();
// Somewhere here set the $_GET['variable'];
$.ajax({
type: 'POST',
url: 'http://localhost/app/comment/comment.func.php',
data: 'comment='+comment,
success: function(data) {
$('#replies').html(data);
}
});
});
});
If I understand what you are trying to do correctly, you can try something like this to use server-side PHP variables in your client-side javascript.
var comment = $('#place_comment').val();
var myVariable = '<?php echo $_GET['variable'] ?>';
You can't do this like this : javascript is client-side and PHP $SERVER array is server-side.