Trigger JQuery function based on value of variable - php

I have a page that receives incoming values from $_POST. One such value is from a drop down selector that allowed the user to select values 0 -10. I want to trigger a JQuery function if a value greater than 0 was selected.
So, if $_POST['DropDownSelection'] > 0, then my JQuery function should run.
How do I trigger the function?

If the function needs to be called in the original page then you can do this -
$('select[name="DropDownSelection"]').change(function() {
var newValue = $(this).val();
if(newValue > 0) {
// your function here
}
});
You don't need PHP, you just need to see if the value changed and then if the value is greater than 0.
If the function is in the page that gets posted to then you could do this -
<script>
var DropDownSelection = <?php echo $_POST['DropDownSelection']; ?>;
if(DropDownSelection > 0) {
// call your function here
}
</script>

Something i like to do for passing a PHP var to Javascript is to put in in an hidden input like that :
<input id="myValue" type="hidden" value="<?= $_POST['DropDownSelection']; ?>" />
The in your javascript :
if(document.getElementById('myValue').value > 0) //Do something

Depends on how your PHP code is connected to the HTML output. In the simplest case where PHP and HTML are in the same file, you could do something like
<? if ($_POST['DropDownSelection'] > 0) { ?>
<script>$.myFunction(...);</script>
<? } ?>

You can do like that.
var x = <?php echo $_POST['DropDownSelection'] ?>;
if(x>0){
jqueryFunction(); // your function call.
}else{
// whatever else you want.
}

Maybe this is oversimplified and a little hacky, but I don't see why this wouldn't work...
<script type="text/javascript">
function overZero() {
// do stuff...
}
<?php
if ($_POST['DropDownSelection']>0) echo('overZero();');
?>
</script>

$(document).ready(function(){
$("#dropdown-id").change(function(){
//check if the value is > 0 and then
// trigger your jquery function()
})
})

However, I want to also call that function when the user lands on the page with
a particular $_POST value for a field
There are 2 easy ways of doing this:
Make global funciton:
ex:
function print(){
alert('hello')
}
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>print()</script>";
}
?>
Or use triger function from jquery:
<?php
if($_POST['DropDownSelection'] != 0)
{
echo "<script>$('#dropdown').trigger('change');</script>";// execute the onchange event(function) attached to the dropdown
}
?>

Related

Parsing div id with variable

First of all I appreciate that all members are trying to help each other.
I want div content by id in my javascript function. I've got function and it works fine with one div and it's content. But now I've got multiple records from DB, so to make div unique I have done following. where $i=$i+1 in while loop
<div id="<?php echo 'fvd'.$i; ?>" class="fake-checkbox star-checkbox"><a id="<?php echo 'tvd'.$i; ?>" onclick="respuestas('<?php echo $user_id1;?>'); return false;" href="#">Add to favourites</a></div>
so here I generate fvd1, tvd1 for next record fvd2,tv2 and so on
Below function process user id and get response by Ajax call and change caption from Add to favourites to Added to favourites and add class name 'checked' which change text color.
function respuestas(str) {
var popID = str;
var gett = document.getElementById('tvd1').innerHTML;
if (gett == 'Add to favourites') {
$.post('personals/addfavourite.php', {
ref: popID
}, function (data) {
if (data == 'no') {
alert('Sorry! something gone wrong!')
} else if (data == 'yes') {
var d = document.getElementById("fvd1");
d.className = d.className + " checked";
document.getElementById('tvd1').innerHTML = 'Added to favourites';
}
});
}
}
Now how can I parse fvd2,tvd2 and so on in this function.
Any help will be much appreciated..Thanks
If you add your $i to the function parameters you can get each grouping dynamically
onclick="respuestas('<?php echo $user_id1;?>',<?php echo $i;?>); return false;"
and
function respuestas(str,num) {
...
var gett = document.getElementById('tvd'+num).innerHTML;
...
var d = document.getElementById("fvd"+num);
...
document.getElementById('tvd'+num).innerHTML = 'Added to favourites';
...
}
You can do
onclick="respuestas(this, '<?php echo $user_id1;?>');
and the first param would be the <a> so you can do
function respuestas(elm, str) {
elm.getAttribute("id");
}
or so. (Not sure about the DOM method name)
BTW why don't you just put the $i to the call as well? Or maybe I didn't get the question right? If not, pls explain.
If you need to access the elements, well then you already have the <a> in elm, and the <div> is in elm.parentElement.
Check HTML DOM methods: https://developer.mozilla.org/en-US/docs/Web/API/Node.parentElement

javascript:variable value passing from javascript to php

I have a javascript file pet.js. I want to pass a value of variable in test.php. But i can't.
my pet.js is like
$('#pmWorkOrderDetailsPage').live('pageshow', function(event) {
var id = getUrlVars()["id"];
$.get("test.php", { test1: id } );
$.getJSON('pmworkorderdetails.php?id='+id, displaypmWODetails);
});
function displaypmWODetails(data) {
..............code..........
}
My test.php is like
<?php
$ms = $_GET["test1"];
echo $ms;
?>
But it is not working. I tried with Ajax and post method.
It will be best if I can store the variable value on the session in test.php.
Thanks in advance for any help.
1 do not use getUrlVars() it can make site vulnerable to xss
$('#pmWorkOrderDetailsPage').live('click', function(event) {
var id;// get id
$.get("test.php?id="+id,function(data){
var result=$.parseJSON(data);
alert(result["content"])
});
})
test.php
<?php
$id=$_GET['id'];
$data=array();
$data=array("content"=>$id);
echo json_encode($data);
?>

Getting through the DOM from the file to which I did a post request through ajax

I used this simplify examples to explain better the question.
given the following post request under ajax:
$(document).ready(function()
{
$(#submit).click(function()
{
$var = $("#result");
$code = $("#code");
$.post("ajax.php", {option : $var, code: $code}, function()
{
//Getting through the DOM could be useful if you want to analyse the answer coming from the ajax.php file
var $DOMresponse = getElementByTagName("div")[0].firstChild.data; // I would want the correct code here because this is incorrect... this is ti give you an idea
if($DOMresponse == "your code is correct")
{
$("#container1").fadeOut(400, function(){ $("#container1").html(result); });
$("#container1").fadeIn();
}
elseif($DOMresponse == "your code is incorrect. Go again trough the procedure")
{
$("#container2").fadeOut(400, function(){ $("#container2").html(result); });
$("#container2").fadeIn();
}
// In this second case I could fill the second container id="container2"
});
});
});
ajax.php example:
<?php
if($_POST['request']==1)
{
if($_POST['code']==$user['code'])
{
?><img src="...">
<div>tomatoes</div>
<div>potatoes</div>
<div id="answer">your code is correct</div> <?php
}
else
{
?><img src="...">
<div>apples</div>
<div>oranges</div>
<div>your code is incorrect. Go again trough the procedure</div> <?php
}
}
I would like to know how to get through the DOM of the ajax.php file.
how do I do this? Thanks
Do you need to do this before inserting the result to the page? If so create new element and insert the result to it. For example
var div = document.createElement('div');
var obj = $(div).html(response);
Now you have a standard jQuery object with the dom element.
Responding to the comment:
I am confused. Do you want to validate the code in php or js? It looks like your checking if what is send through post is the same as defined in $user variable. So validating the code is done in php. In that case wouldn't be simpler to use json as a response. In php script create result array with key status set to 1 or 0. In post resposne you can check response.status == 0.
Other wise it look just strange that you make the validation once in php and the twice in js after response. Besides if you set your response to be standard text then you have to create dom element and place the reponse inside to be able to search through it.
I think what you're asking is how do you get the value of $('#code') in the ajax.php file.
Here's what you're doing:
var $code = $('#code'); // jQuery object
$.post('ajax.php', { code: $code });
The problem with this is that you're passing the entire jQuery object to ajax.php. What you probably want to do is pass the value or html of the $('#code') object, like so:
var code = $('#code').html(); // if it's a non-input element
var code = $('#code').val(); // if it's an input
$.post('ajax.php', { code: code });
Then in the ajax.php file, your $_POST['code'] will equal the value of code (e.g. "ABC123"), which you can then use to compare with $user['code'] or whatever you want.
I hope I understand the problem correctly. Good luck.
EDIT: I think I understand what you're getting at now. What you want to do is this:
HTML:
Javascript:
var $option = 'request';
var $code = $('#code').val();
$.post('ajax.php', { option: $option, code: $code }, function(data) {
if (data == 'valid') {
// show valid code result here
} else {
// show invalid code result here
}
});
and ajax.php
<? if ($_POST['option'] == 'request') {
if ($_POST['code'] == '123ABC') {
echo 'valid';
} else {
echo 'invalid';
}
}
?>
Notice that the variable data comes from the function(data) part in the $.post parameter. That data variable contains the response from ajax.php (in my example, it would be 'valid'.)

show hidden div section based on if statement

I have a few hidden divs on page like this
<div class="form" id="scheduler" style="display: none;">
<div class="form" id="test" style="display: none;">
<div class="form" id="super" style="display: none;">
I would like a jscript which can be called to show these hidden divs based on criteria like this
<?php
if ($_GET['id'] == 'scheduler') {
call jscript function (show div id:scheduler in this case)
}
else if ($_GET['id'] == 'test') {
call jscript function (show div id:test in this case)
}
else if ($_GET['id'] == 'super') {
call jscript function (show div id:super in this case)
}
?>
thanks.
you cannot call javascript function from PHP, PHP is server side based and stands for Preprocesing Hypertext while Javascript is browser based.
You could use:
<?php
if ($_GET['id'] == 'scheduler') {
$showdiv = 'scheduler';
}
else if ($_GET['id'] == 'test') {
$showdiv = 'test';
}
else if ($_GET['id'] == 'super') {
$showdiv = 'super';
}
echo "<script type=\"text/javascript\">document.getElementById('".$showdiv."').style.display = 'block';</script>";
?>
but that should be at bottom of the page, after those divs are loaded.
<script type='text/javascript'>
function showDivById(id){
document.getElementById(id).visible = true;
}
<?php
$divs = array('scheduler','test','super');
if (array_seach($_GET['id'], $divs)!==false)
echo "showDivById({$_GET['id']})";
?>
</script>
Note that php code is within the <script>
Why don't you write your function to accept the id param of the query string?
<script>thefunction($get);</script>
This way you can save on if logic, and develop a more abstract function. It's less code, and easier to manage.
First of all. I would use jquery to show/hide divs...
but my concept would be a bit different then above,
<?php
if($_GET['id']){
echo '<script type="text/javascript">$(\'#'.$_GET['id'].'\').show();</script>';
}
?>
Hope that you got my idea, it's clean and pretty dynamic :)
Even though you've accepted an answer, another option would be to use only JavaScript with the aid of some JS to easily retrieve values from the query string.
function $get(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
}
var qs_id = $get('id');
if (['scheduler', 'test', 'super'].indexOf(qs_id) >= 0) {
document.getElementById(qs_id).style.display = 'block';
}
Demo: jsfiddle.net/Marcel/L69xt/show

loading a returned value from php into a js variable using ajax and jquery

Basically all i wanna do is something like this.
var myVar = $.load("phpscript.php","var=one");
phpscript.php
<?
$a = $_GET['var'];
if($a == "one") { return 1 };
else return false;
?>
Right now i am doing this the most idiotic way as i cannot find out how to do this the proper way. what i am doing currently is making my phpscript return a hidden field with the value
return "<input type='hidden' value='1' id='takeValueFromThisID>";
into a div from the calling page and finally use the above id to retrieve the value. Even though this works its very idiotic. Can some one pls guide me in the right way to do it.
$.get("phpscript.php", { 'var': 'one' }, function(resp) {
alert(resp); // '1'
});
and a test PHP script:
<?php
echo '1';
?>
PHP Code
<?
$a = $_GET['var'];
if($a == 'one') {
echo 1
} else {
echo 0; // or '' may be?
}
?>
AJAX
var myVar;
$.get("phpscript.php", {"var": "one"}, function (resp) {
myVar = resp;
});
The problem here is that myVar will be "1" or whatever after the AJAX request is completed. This may take a couple of milliseconds (or seconds). If you plan to use myVar in your script you must wait until it becomes something other than undefined.

Categories