JQuery (UI): Javascript Variable convert to PHP Variable - php

First of all.. is this possible? I work&create a var in javascript (jquery ui framework) and then when I click on the "Submit" button of my form it should this variable?
HTML & Javascript (Jquery UI):
<script>
$(document).ready(function() {
var slider1 = $( "#slider1" ).slider( "value" );
var slider2 = $( "#slider2" ).slider( "value" );
});
</script>
pseudo: HTML & PHP:
<?php echo slider1 ?>
How can I echo the value of #slider1 ??

You cannot assign a variable from javascript to php, but you can set a javascript variable to a form input element before you send the form, then you can get the values via the $_POST or $_GET (or the $_REQUEST) superglobal arrays, based on your method ().
http://php.net/manual/en/reserved.variables.get.php
http://php.net/manual/en/reserved.variables.post.php
For example:
Javascript:
$(document).ready(function(){
var test = "test";
$('#someinput').value(test);
});
Html:
<form action="some.php" method="post">
<input type="hidden" id="someinput" name="someinput"/>
<input type="submit" value="send"/>
</form>
PHP:
<?php
var_dump($_POST['someinput']);
?>

Mike you cannot mix server side code with client side code. They are completely seperate!
What you can do is just before the form posts put some value inside a hidden input and check it on the server side

add it to hidden input in your form
like
$('#hidden_field').val(slider1)

You are misunderstanding how PHP and Javascript work. PHP runs on the server, JavaScript runs on the browser. When JavaScript runs, PHP is already done generating the document.
If you have a JavaScript variable, you need to use JavaScript to alter the element.
For example:
<div id="slider_value"></div>
<script>
$(document).ready(function() {
var slider1 = $( "#slider1" ).slider( "value" );
var slider2 = $( "#slider2" ).slider( "value" );
// Assign value to DIV
$("#slider_value").html("Value: "+slider1);
});
</script>

Related

How to pass a PHP variable to a .JS file using JQUERY?

I'm a JQUERY begginner. I'm trying to pass a PHP variable to a js file so that i can use it in JQUERY! But found no resource to learn to do so. I'm able to pass a JQUERY variable to a different php file but I couldn't pass PHP variable to a Jquery file. Is really possible to do so?
function.php:
<?php $variable = $fetch['username']; ?>
app.js : How can use this variable in app.js file below?
$(document).ready(function(){
var flwbtn = $(".findrowpplfollowbtn");
flwbtn.click(function(){
var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
$.post("../php/flw.php",{flwusernameselected:selectflwusername})
});
});
Echo it to HTML temaplate. If it's some structure/array use for example json format.
<script>
<?php $variable = $fetch['username']; ?>
var js_variable = <?php echo json_encode($variable); ?>
</script>
or
echo some hidden element like
<input type="hidden" id="custId" name="custId" value="<?php echo($fetch['username']); ?>">
and grab if with Jquery like
<script>
$( "#custId" ).value();
</script>
with your code
JS:
$(document).ready(function(){ var flwbtn = $(".findrowpplfollowbtn");
flwbtn.click(function(){
var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
$.post("../php/flw.php",{$( "#custId" ).value()})
});
});

How to POST values stored in href link in one page to the next php page

I have several links in a HTML/PHP page and I want to pass the value stored in the link when they are clicked to the next PHP page via $_POST (I know how to do it with $_GET but that is not what I want).
I know I need to use javascript/jquery and I have tried a lot of different things but I haven't been able to get it working. I can add an onclick attribute to href, if it helps to solve the problem.
INSIDE "page1.php" or "page1.html"
// Send the values of variables var1, var2, etc. to the new PHP page...
<div class="super">
good
</div>
<div class="super">
better
</div>
<div class="super">
best
</div>
<script>
(function() {
$("#id").on("click",function(e) {
e.preventDefault();
$.post(this.href,function(value) {
$(".top").html(value);
});
});
});
</script>
INSIDE "page2.php"
<?php
// Retrieve the URL variables (using PHP and jquery).
$val_1= $_POST['var1'];
$val_2= $_POST['var2'];
$val_3= $_POST['var3'];
//to test we retrieved the values from page1
echo "value of var1 is: ".$var_1;
?>
The issue is because you're not sending any data in the $.post call. Presumably you want to send the id/value of the a elements.
Firstly, note that value is not a valid attribute of an a element. I'd suggest changing this to a data attribute to avoid validation issues.
Secondly, to send the data in the request you can build an object, like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="super">
good
</div>
<div class="super">
better
</div>
<div class="super">
best
</div>
<button id="id">Click me!</button>
<script>
$(function() {
$("#id").on("click", function(e) {
e.preventDefault();
var data = {};
$('a').each(function() {
data[this.id] = $(this).data('value');
});
console.log(data);
$.post(this.href, data, function(value) {
$(".top").html(value);
});
});
});
</script>
** Update **
When any of the href link is clicked, page2.php is opened and based on which linked is clicked e.g. 'link3 above' which has a value 300, the page2.php does something based on that value. I don't want to pass all values of the links at once
In this case you can just read the data-value from the element and send it in the request and read it back in the PHP:
$(function() {
$(".super a").on("click", function(e) {
e.preventDefault();
$.post(this.href, {
value: $(this).data('value')
}, function(value) {
$(".top").html(value);
});
});
});
<?php
$val = $_POST['value'];
echo "value of var1 is: ".$val;
?>
var value= $(this).attr('value');
After that pass thus value to ajax function.
Example:
var record_id=jQuery(this).attr('data-key');
jQuery.ajax({
url: url,
dataType:'json',
type: "POST",
data:{
record_id:record_id,
}

$.post - trying to echo textbox value to div

I want after I type text in the textbox and click the button for that text to appear in the div above the form but I keep getting a php error undefined index: chattext
HTML:
<div class="chatdiv"></div>
<form id="chatform" action="chat.php" method="post">
<textarea name="chattext"></textarea>
<button>Send</button>
</form>
CHAT.PHP
<?php
echo $_POST['chattext'];
?>
JQUERY:
$(function () {
$('button').on('click', function(e) {
$.post('chat.php', $(this).serialize(), function(data) {
$('.chatdiv').html(data);
});
e.preventDefault();
});
}); // end ready
You are serializing the button:
$(this).serialize()
not the form. Change it to:
$("#chatform").serialize()
For future reference, when you're getting little issues like this, take a look at your web browsers developers tool, under network. It will show you what data is being posted to the web server.
You're not referencing the form in serialize(), the line should be:
$('#chatform').serialize()
You need to bind the event listener to your form in order to use $(this).serialize();
$('form#chatform').on('submit', function(e) {

Pre-fill a form (no control over form code)

I'm using a form plugin / addon where I don't have control over how the form is generated.
The form generates HTML which looks like this:
<form>
<label>First Name</label><input name="Question25" type="text" value="" />
<input class="formBlockSubmitButton" name="add" type="submit" value="Submit" />
</form>
I would like to prefill some of the form values but I can't write, say
<input name="Question25" type="text" value="<?php echo $my_value; ?>" />
Because the form addon generates that HTML. I can write PHP or Javascript before this block, is there a way to search for an input with a name of "Question25" and then prefill it when the block comes up?
You could use jQuery and the .val() method:
<script type="text/javascript">
$(function() {
$('input[name="Question25"]').val('some value');
});
</script>
and if the value must come from the server:
<script type="text/javascript">
$(function() {
var obj = <?php echo json_encode(array('value' => $my_value)); ?>;
$('input[name="Question25"]').val(obj.value);
});
</script>
You can emit all the values you'd like to search as an array of fieldname/values, and then emit a function that tries to map those values to those fields.
<script type="text/javascript">
var values = [{fieldName:'Question25', value:'MyValue'}]; // iterate through your values in PHP and generate the {fieldName:'value',value:'value'} object
$(function() {
$.each(values, function(index, item) {
$('input[name=' + item.fieldName + ']').val(item.value);
});
});
</script>
var value='<?php echo $my_value; ?>'
$("input:text[name='Question25']").val(value);
use something like this
Use Javascript. With jQuery, you could do something along the lines of:
$("input[name=Question25]").val(my_value);
You can then insert PHP vairables into the Javascript with echo, load them with AJAX, or whatever you need.

jQuery & AJAX -- populating a list?

I've made jQuery & AJAX script that uses a PHP function to bring back results from an API. That part works great, but everytime I search for a new book, it removes the previous search results.
I want to give it a book ID, search, get results, and continue doing that. Every time I click "search", I want to populate a list with more books.
This code keeps removing my previous book and replacing it with the new book I've searched for.
Any ideas?
isbn.php:
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<form method="post" action="ajax.php" id="searchForm">
<input type="text" name="isbn" placeholder="Search..." />
<input class="myaccount" id="doSearch" name="doSearch" type="submit" value="Search" />
</form>
<div id="result"></div>
{literal}
<script>
// attach a submit handler to the form
$("#searchForm").submit(function(event) {
// stop form from submitting normally
event.preventDefault();
// get some values from elements on the page:
var $form = $( this ),
term = $form.find( 'input[name="isbn"]' ).val(),
//term = "isbn",
url = $form.attr( 'action' );
$.post( url, { doSearch: "Search", isbn: term } ,
function( data ) {
var content = $( data );
$( "#result" ).html( content );
}
);
});
</script>
ajax.php does the API call and prints the results inside of isbn.php.
if you are just trying to append the content then:
$( "#result" ).append( content );
if you want the new results to go to the top of the results div then
$( "#result" ).prepend( content );
using $( "#result" ).html( content ); tells jQuery to replace the entirety of any HTML inside #result with the new content
The problem is in your ajax success function you are rewriting the entire content of the #result block. If you changed .html to .append this should just make it additive rather than replacing.

Categories