Using if statement in ajax using values from the database - php

I have column name status in Database it contains values(0,1) ,in front end i have image if i click the image it will redirect to the next page i am using ajax here, what i want before redirect it should perform if condition i want to check the database column status if the column contain any row '1' it should redirect if all rows in column '0' its not checking the if condition it will redirecting can anyone guide me how to perform this .below is my code(i.e now in row status all values are 0 it will not redirect it want to show alert but its redirecting)
html
<img id='redirect' src="/image/exporttt.png" style="margin:-30 0 0 0px;cursor:pointer;" >
$sql_selectsupplier = "********";
$result1 = mysql_query($sql_selectsupplier);
while($rows=mysql_fetch_array($result1))
{
$reditect=$rows['status'];
}
Ajax
<script>
$(document).ready(function() {
$("#redirect").click(function() {
if($reditect=1){
var clientid=document.getElementById("client").value;
$.blockUI(
{
message: '<h2>Please wait...</h2><img src="/image/loader.gif" />',
timeout: 2000
});
$.ajax({
type:"post",
data:"clientid="+clientid,
success:function(data){
window.location = '?action=clientroutingchange&clientid='+clientid+'';
$("#result").html(data);
$('.blockUI').hide();
}
});
}
else{
alert("no changes made")
}
});
});
</script>

From your code it's not clear which one is PHP code, and which one is out of the PHP block.
Inside your block you have
if($reditect=1){ which does not seem like a javascript code.
Is that php?
If yes, then you are using it wrong way. = is an assignation operator, so you do assign the value 1 explicitly this way.
I would suggest, if you are using PHP conditions, also to move thme outside the script block:
<?php if ($reditect == 1): ?> # `==` for comparison
<script>
var clientid=document.getElementById("client").value;
// .. all the code
</script>
<?php else: ?>
<script>
alert('.....');
</script>
<?php endif; ?>
If it was an Javascript condition, then you need to assign the value of the php variable to the js var
<script>
var reditect = "<?= $reditect; ?>";
if (reditect == '1') {
// something
</script>

Use == for comparision
if($reditect==1)
and your $redirect is a php variable which doesn't make sense in script
So, use
var reditect = <?php echo $reditect ?>
and check by,
if(reditect==1)

Related

Ajax Posting of data to PHP

I have the following code:
<?php
$query=mysqli_query($mysqli, "SELECT assignment,a_id FROM assignments WHERE groupid='".$groupid."'");
$assignments = array(); // create empty assignments array
while ($row=mysqli_fetch_array($query)){
echo'<td class="columnname" id="'.$row['a_id'].'" contenteditable="true">'.$row['assignment'].'</td>';
$assignments[$row['a_id']] = $row['assignment']; // add assignment to array
}
?>
<script>
$('.columnname').keyup(function() {
delay(function(){
var text= $(this).text();
var id= $(this).attr('id')
$.ajax({
type:"POST",
url:"updateassignment.php",
data:{text:text, id:id},
success:function(data){
console.log('success bro!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
Basically what happens, is that i have a contenteditable and whenever that is keyup (which means whenever user types in info), it will post the data to the php file updateassignment.php which updates the values. However, it doesnt seem to work for me, it gives me the success result, but shows no error. Its sort of not getting the values from the fields, but as you can see, im using $(this) which refers to the columnname class (which is generated dynamically by php)
The php updateassignment file code is below:
<?php
include_once("config.php");
if (isset($_POST['id']) && isset($_POST['text'])) {
$id=$_POST['id'];
$text=$_POST['text'];
$query=mysqli_query($mysqli, "UPDATE assignments SET assignment='$text' WHERE a_id='$id'")or die(mysqli_error($mysqli));
}
?>
I have a feeling that the this is not refering the correct element, therefore contenteditable's ajax is unable to grab the correct value.
I found the answer.
It was because i defined the ajax this inside the delay function, so it would not reference the columnname. The way to solve this is to define $(this) outside of the delay function.

display data via ajax when using $_GET

How do I display data based on `$_GET', which is to say without refreshing the page ?
I have this for example, and it shows the correct result whenever I click add (increments by 1), but of course it always first refreshes the page.
How do I make it do the same thing without visible page refresh, using ajax?
php and html
if (isset($_GET['add'])) {
$_SESSION['numbers']++;
}
echo $_SESSION['numbers'];
?>
<br>
add
<div id="response"></div>
And if for example I wanted to pull something from the database via post and print it, I would do something like this:
$.post('print_something.php', function(response) {
$('#response').html(response);
});
But how do I change that for get, since there is stuff in the URL plus sessions?
EDIT:
I tried this, I removed all php from the current script, added it to get.php which is now like this:
session_start();
if (isset($_GET['add'])) {
$_SESSION['numbers']++;
}
echo $_SESSION['numbers'];
And inside my main index script I have this:
$('a.add').click(function() {
$.get('get.php', function(response) {
$('#response').html(response);
});
return false;
});
Now it does not increment each time i click add, it just shows 1 the first time and doesn't change afterwards.
You are not passing the add parameter to your $.get, so isset($_GET['add']) is false. Add add to your ajax call
$.get('get.php', {add:true}, function(response) {
$('#response').html(response);
});
I put {add:true}, but true could be anything, as you are only checking if it is set, not the value
alternatively, you could also just add it to your url
$.get('get.php?add=true', function(response) {
$('#response').html(response);
});
Please find the example code below:
$('a.add').click(function(e) {
e.preventDefault();
var request = $.ajax({
url:"get.php", //Please provide the absolute URL to avoid errors.
type:"GET",
data:""
});
request.done(function(response){
$("#response").empty().html(response);
});
});

How to write if else if statement in jquery where condition set by wordpress option setting

How to pass wordpress option setting value as condition to toggle jquery function using if else statement?
Wordpress option setting value is 'select-type' value which is grabbed in my template using
<?php echo get_option('my_animation_module') ?>
which may print only one value like animation1, animation2, animation3 and so far..
I want to pass this option value as a condition in jquery to get diffrent animation effect using this wordpress option value.
HTML :
<div id="content-page>
<img src="images/myimage.png"/>
<div>
Jquery :
$(document).ready(function(){
$('#content-page').hover(function() {
$(this).find('img').stop(false,true).animate({'top':480, 'left':270}, {duration:600});
},
function() {
$(this).find('img').stop(false,true).animate({'top':0, 'left':270}, {duration:500});
});
});
This is my first sample animation effect using jQuery. I want to add diffrent animation effect on image and those get shuffled using if else statement in jQuery and wordpress option value as condition.
$(document).ready(function(){
if('<?php echo get_option('my_animation_module') ?>' == "animation1")
{
//js code for animation1
}
else if('<?php echo get_option('my_animation_module') ?>' == "animation2")
{
//js code for animation2
}
else if('<?php echo get_option('my_animation_module') ?>' == "animation3")
{
//js code for animation3
}
});
Updated answer as requested
Can I grab this option value in jQuery by storing it as a variable ? Yes. See the eg.
var myval = '<?php echo get_option('my_animation_module') ?>';
alert(myval);
If your jQuery code is small, you can put it inline IN THE BOTTOM of the HTML document, just before < /html >, then echo PHP data as Dasun showed.
If your code is bigger, u'd better put it in a separated js file. To send data to that code in the file, in HTML document you just set a JS variable with the data, and in the main code uou test if that variable was set and if so you process it.
<script>
var mydata = <?php echo $mydata; ?>;
</script>

Best way to refresh multiple PHP values every x seconds?

I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/

Javascript function only outputs value of first check box from a PHP for loop

I have a for loop that forms a list of check boxes based on information received from a mySQL database. Below is the for loop that forms the check boxes (unnecessary code removed).
for ($i = 1; $i <= count($descriptionIDsArray); $i++) {
$statuses = mysql_fetch_assoc(mysql_query(sprintf("SELECT status, description FROM status_descriptions WHERE description_id='$i'")));
$status = $statuses["status"]; ?>
<input type="checkbox" value="<?php echo $status ?>" <?php if ($check == 1) {echo "checked='checked'";} ?> onchange="checkBox()" /><?php echo $description ?><br />
<?php } ?>
Checking or unchecking a box calls the following function:
<script type="text/javascript">
function checkBox() {
var status = $("input:checkbox").val();
document.getElementById("test").innerHTML = status;
}
</script>
The only value that I can get to appear in "test" is the value of the first check box. If I echo $status throughout the initial for loop all the values appear correctly so the problem seems to arise when the Javascript code is retrieving the corresponding value.
If you still want to keep the inline event handlers, change it to:
onclick="checkBox(this);"
And change the function to:
function checkBox(chk) {
var status = chk.value;
document.getElementById("test").innerHTML = status;
}
Note that onclick is better supported with checkboxes and radio buttons than is onchange. Also, the reason for this change I provided is because passing this to the checkBox function references the element that the click was applied to. That way, you know that inside of checkBox, the parameter chk will be the specific checkbox that just changed. Then just get the value with .value because it's a simple DOM node.
Anyways, I'd suggest using jQuery to bind the click event. Something like:
$(document).ready(function () {
$("input:checkbox").on("click", function () {
var status = this.value;
document.getElementById("test").innerHTML = status;
});
});
But you can obviously use $(this).val() instead of this.value, but why bother? If you use jQuery to bind the events, just make sure you take out the onchange/onclick inline event handler in the HTML.
You can look at why to use input:checkbox and not just :checkbox as the jQuery selector here: http://api.jquery.com/checkbox-selector/
When you do
$('input:checkbox').val();
it is returning the first input of type checkbox on your form, not necessarily the one that is clicked.
To return the one that was actually clicked, you need to do something like this:
$(document).ready(function() {
$('input:checkbox').bind('click', function() {
clickBox($(this));
});
});
function clickBox(field) {
$('#test').html(field.val());
}
if you use a jquery, why bother with inline events?
You could write that like:
$(':checkbox').change( function(){
$('#test').html( $(this).val() );
//`this` is the checkbox was changed
//for check if item is checked try:
$(this).is(':checked') // boolean
});
If you pass that code before your checkboxes are placed make sure you invoke that code when document is loaded;
$( function(){
//code from above here
});
jQuery is well documented with lots of samples.
I think you'll like it docs.jquery.com

Categories