Echo jQuery loop using PHP - php

After searching for a long time I've decided to just ask it here, since the things I found either don't work(or I can't get them to work ;)) - or require me to change things on my server, which I would like to avoid.
I want below function to show the output after each result, so the function doesn't have to be loaded first, which takes a long time. My idea, as you can see below, was to try this with jQuery(1.8.2).
It doesn't work and I simply can't get it to work. Is there a better way to do this? Did I make a mistake somewhere causing it not to work?
If you need additional information, please ask.
<?php
print_r($_POST);
if(isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option']))
{ error_reporting(0);
define('INCLUDE_CHECK',true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.',$_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
if ($_POST['loop']==40)
{ print 'Laatste loop dus .. STOP : .'.$ext[41]; }
else
{ print 'Loop: '.$_POST['loop'].' - zoek op : .'.$ext[$_POST['loop']];
?>
<script>
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $_POST['loop']+1; ?>'},
function(data){
$('#domresults2').css('display','block').html(data);
$('#domloading').css('display','none');
});
</script>
<?php
}
}
?>
//Start JS
<script>
$('#domsubmit.complete').click( function() {
var dom = escape($('#domsearch').val());
var opt = escape($('#option').val());
$('#domresults2').css('display','none').html('');
$('#domloading').css('display','inline');
$.post('test.php', { p:'full', domain:dom, option:opt, loop:0},
function(data){
$('#domloading').css('display','none');
$('#domresults2').css('display','block').html(data);
});
return false;
});
</script>
//end JS
///////////////////////////
update : solved!
so, what went wrong? -> the php function in core.inc.php referred to a incompatible with jQuery 1.8.2 lib ('qTip2'). Thanks for the support!
<?php
print_r($_POST);
if (isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option'])) {
error_reporting(0);
define('INCLUDE_CHECK', true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.', $_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
$loop = $_POST['loop'];
DomCheck($_POST['domain'],$ext[$_POST['loop']]);
if ($loop != count($ext)) {
$loop++;?>
<script type="text/javascript">
var opt = '<?php echo $_POST['option']; ?>';
var dom = '<?php echo $_POST['domain']; ?>';
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $loop; ?>'},
function(data){
$('#domresults2').css('display','block').append(data);
<?php if ($loop < count($ext)) {
echo "$('#domloading').css('display','none');";
} ?>
});
</script>
<?php
}
}
?>

One thing you need to understand is that PHP executes on the server and JavaScript (jQuery) executes on the client.
This means that by the time jQuery starts executing, PHP is done.
However, I don't see a loop anywhere in your code. I think this is more of what you wanted. You're not doing a "PHP loop using jQuery," you're outputting jQuery code in a PHP loop:
<?php
if (isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option'])) {
error_reporting(0);
define('INCLUDE_CHECK', true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.', $_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
foreach ($_POST['loop'] as $loop) {
if ($loop == 40) {
print "Laatste loop dus .. STOP : .{$ext[41]}";
} else {
print "Loop: {$loop} - zoek op : .{$ext[$loop]}";
?> <script>
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $loop; ?>'},
function(data){
$('#domresults2').css('display','block').html(data);
$('#domloading').css('display','none');
});
</script>
<?php }
}
}
?>

Related

WP Ajax not working in else condition

I am working on WordPress plugin. In plugin there is a check box, when a user checked the checkbox a value will be saved in database via ajax and when its unchecked the value will be deleted from database via ajax. So I create a checkbox and write an ajax code.
Here is my code:
HTML Code
<?php
$cart_items = get_cart_contents();
$cart_info = array();
foreach ($cart_items as $_data) {
$prod_id = $_data['id'];
$cart_info[] = array(
'prod_id' => $prod_id,
);
}
$_cart_sr = serialize($cart_info);
?>
<label class="label" for="purchase">
<?php _e('Purchase', 'product'); ?>
<input type="checkbox" id="purchase" />
</label>
<input type="hidden" class="cart_info" value='<?php echo $_cart_sr; ?>'>
Here is my Ajax and PHP Code:
add_action('wp_ajax_values_save', 'save_check_value');
add_action('wp_ajax_nopriv_values_save', 'save_check_value');
add_action('wp_ajax_values_delete', 'delete_check_value');
add_action('wp_ajax_nopriv_values_delete', 'delete_check_value');
add_action("wp_head", "edd_gift_email_ajax");
function edd_gift_email_ajax() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#purchase").click(function () {
if(jQuery(this).is(":checked")) {
var cart_info_save = jQuery('.cart_info').val();
var data_save = {
action: 'values_save',
cart_info_save: cart_info_save
}
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data_save, function (save_result) {
alert(save_result);
});
} else {
var cart_info_delete = jQuery('.cart_info').val();
var data_delete = {
action: 'values_delete',
cart_info_delete: cart_info_delete
}
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data_delete, function (delete_result) {
alert(delete_result);
});
}
});
});
</script>
<?php
}
And here is my save and delete query
function save_check_value() {
global $wpdb;
$info_save = stripcslashes($_REQUEST['cart_info_save']);
$cart_info_un_sr_save = unserialize($info_save);
foreach ($cart_info_un_sr_save as $user_gift_cart_save) {
$prod_user_id_save = $user_cart_save['prod_id'];
echo $prod_user_id_save . " _ Add This";
//update_post_meta($prod_user_id_save, 'this_product', '1');
}
}
function delete_check_value() {
global $wpdb;
$info_delete = stripcslashes($_REQUEST['cart_info_delete']);
$cart_info_un_sr_delete = unserialize($info_delete);
foreach ($cart_info_un_sr_delete as $user_cart_delete) {
$prod_user_id_delete = $user_cart_delete['prod_id'];
echo $prod_user_id_delete . " _ Delete This";
//delete_post_meta($prod_user_id_delete, 'this_product', '1');
}
}
So when I checked the check box the alert gives me this value 168 _ Add This (this is what I want) but when I unchecked the check box the alert gives me this value 0 (I want this value 168 _ Delete This).
I checked every thing but I got confused that why else condition not give me the right value.
Any suggestions.
Not directly a solution but I can't help thinking there is quite a lot of duplication of code which could be somewhat simplified.
The initial javascript function could be like:
<script type="text/javascript">
jQuery( document ).ready(function() {
jQuery("#purchase").click( function() {
var action=jQuery(this).is(":checked") ? 'save' : 'delete';
var cart_info=jQuery('.cart_info').val();
var data={
action:'value_'+action,
cart_info:cart_info
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function( result ) {
alert( result );
});
}
});
});
</script>
And rather than two distinct functions that share almost the same code you could do:
<?php
function check_value() {
global $wpdb;
$info = stripcslashes( $_REQUEST['cart_info'] );
$cart_info = unserialize( $info );
/* To find the `action` analyse the following */
exit( print_r( $cart_info ) );
foreach( $cart_info as $gift ) {
list( $junk, $action ) = explode( '_', $gift['action'] );
$product = $gift['prod_id'];
echo $product . " _ ".$action." this";
switch( $action ){
case 'save':
update_post_meta($product, 'this_product', '1');
break;
case 'delete':
delete_post_meta($product, 'this_product', '1');
break;
}
}
}
?>
The answer of #RamRaider is good but You can still reduce more code and might be it will work for you as well :)
Here's the jQuery:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#purchase").click( function() {
// Method variable will be using to define which
// function should trigger later in our PHP
var cart_method = jQuery(this).is(":checked") ? 'save' : 'delete';
var cart_info = jQuery('.cart_info').val();
var data = {
action: 'modify_cart',
cart_method: cart_method,
cart_info: cart_info
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function( result ) {
alert( result );
});
}
});
});
</script>
And then here is our PHP code:
<?php
function modify_cart_func() {
global $wpdb;
// Get method from our jQuery
$method = $_POST['cart_method'];
$info = stripcslashes( $_REQUEST['cart_info'] );
$cart_info = unserialize( $info );
foreach( $cart_info as $gift ) {
// If method is save
if ($method == 'save') {
update_post_meta($gift['product_id'], 'this_product', 1);
// If method is delete
} else if ($method == 'delete') {
delete_post_meta($gift['product_id'], 'this_product', 1);
}
}
}
?>
And finally your ajax call:
<?php
add_action('wp_ajax_modify_cart', 'modify_cart_func');
add_action('wp_ajax_nopriv_modify_cart', 'modify_cart_func');
?>
Hope that makes sense to you ;)
I am not sure if this causes the problem but if you are calling ajax when not logged in it tries to call wp-ajax with action email_values_delete not values_delete which i guess you are trying to call. Of course you might have that action as well for some other functionality.
If that is not the case change this
add_action('wp_ajax_nopriv_email_values_delete', 'delete_check_value');
To this
add_action('wp_ajax_nopriv_values_delete', 'delete_check_value');
You should also add wp_die(); in the end of each php function you are calling via wp-ajax.
Hope this helps.
Edit:
Sorry, it tries to call values_delete but since there is only email_values_delete (for non logged in users) defined I would guess ajax request might return something like 0.

Stop Execution Php

I have this code , iam trying to use javascript to stop executing but its not working with javascript , any suggestions ? Am just trying to stop executing if the return was false from the javascript
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if (r == true) {
return true;
} else {
return false;
}
}
check();
</script>
<?php
}
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run)die("error".mysql_error());
I am adding sample code to give you an idea, how you could use AJAX Call with it.
<?php
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if(r) {
// Add additional parameter
// You could use POST method too. Use whatever make sense to you.
var urlLink = 'http://www.example.com/warehouse/record.php?from=<?php echo $from?>&to=<?php echo $to?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
return 'You have successfully added new record!';
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
</script>
<?php } ?>
<?php
// -- New File: record.php File
//
// You might wanna add the check, that it's the legit request and all the PHP Validation
$form = $_GET['from'];
$to = $_GET['to'];
$qty = $_GET['qty'];
$codeid = $_GET['codeid'];
$uid = $_GET['uid'];
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run) die("error".mysql_error());
else return 'success';
?>

How do I call a javascript function in a PHP generated script?

I have one problem. I have a popup and after a user creates a room in the popup, I want to close that popup and then redirect the opener window to a new url. I have the function and everything, except for I do not know how to call the function. (Below I have written where I want the function to load).
Thanks
<?php session_start(); ?>
<script type="text/javascript">
function CloseAndRefresh()
{
opener.location.href = "<?php echo $website_url; ?>/livechat.php?idim=<?php echo $perdorusi2; ?>&room=<?php echo $emri; ?>";
opener.focus();
self.close();
}
</script>
<?php
include_once('db.php');
$perdoruesi = $_GET['perdoruesi'];
if( strlen($_SESSION['id']) > '0' ) { $perdorusi2 = $_SESSION['id']; } else { $perdorusi2 = $perdoruesi; }
function makeRandomString($max=8) {
$i = 0;
$possible_keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$keys_length = strlen($possible_keys);
$str = "";
while($i<$max) {
$rand = mt_rand(1,$keys_length-1);
$str.= $possible_keys[$rand];
$i++;
}
return $str;
}
$emri = makeRandomString();
$hidhnedb = mysql_query("INSERT INTO dbname(`row1`, `row2`) VALUES(NULL, '$emri')");
if($hidhnedb) {
$max=count($_SESSION['mysession']);
$i = $max + 1;
$_SESSION['mysession'][$i][$emri] = $emri;
?>
***Here is the the place where I want to call the javascript function but I do not know how to do that.***
<?php
} else { echo "Error!"; }
?>
What you named "popup" is not really clear: is it another browser window ? An window.confirm or window.alert dialog ? a popup like in jQueryUI or Twitter Bootstrap ?
Let's assume it's a browser window.
You have two possibilities:
1 - Make a single button to close your popup:
<button onClick="CloseAndRefresh()">Close</button>
2 - Trigger it automatically after N seconds:
<script type="application/javascript">
var n = 5;
setTimeout(CloseAndRefresh, 1000*n);
</script>
Try
<script type="text/javascript">
CloseAndRefresh();
</script>
Although a PHP redirect would probably fit your purpose better.
Here is an article on PHP redirects:
http://php.about.com/od/learnphp/ht/phpredirection.htm
You can't invoke Javascript functions from PHP as PHP is running on the server, whereas Javascript is downloaded and run on the client, long after the PHP code has executed. You can however print a <script> tag where you, in this case, invoke the Javascript function you want:
<?php
echo '<script>(function () { CloseAndRefresh(); } ());</script>';

Php Sessions and Ajax

Within my index.php file I have an AJAX function that will call a function within another php file which should increment a number and return it whenever i call the AJAX function.
The problem is that the number never changes. I have tried lots of different things. Too many to list them all unfortunately.
My index.php file.
<?php
session_start();
$_SESSION['views'] = 0;
?>
<?php include 'blogFunction.php';?>
<script type="text/javascript">
function doSomething()
{
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
}
</script>
<div class ="blog" id = "blog"></div>
my blogFunction.php
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Right now the output is always '1' whenever i hit the button that calls the AJAX function.
Any help appreciated.
Live Code:here
Thank you all for the help so far. One problem down, a new problem appears.
Extended Functionality:
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$request_url = "http://retrovate.tumblr.com/api/read?type=posts";
$xml = simplexml_load_file($request_url);
$a = $_SESSION['views'];
$b = $_SESSION['views'] +4;
echo "A = ".$a;
echo "B = ".$b;
$_SESSION['views'] = $_SESSION['views']+ 1;
for ($i = $a; $i <= $b; $i=$i+1) {
echo '<h2>'.$xml->posts->post[$i]->{'regular-title'}.'</h2>';
echo '<br>';
echo $xml->posts->post[$i]->{'regular-body'};
echo '<br>';
echo '<br>';
}
}
The problem that lies here, is, I click my button once at my site
and it increments and shows the new content. I click again and it reverts back to 0. If I click the button numerous times fast, it seems to work. It seems that chrome is having this problem whereas Firefox is not.
Add session_start(); to blogFunction.php
Here's the properly working code...
index.php
<?php
session_start();
$_SESSION['views'] = 0;
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js" />
<body>
<div class ="blog" id = "blog"></div>
<input type="button" value="Add to the count!" id="call_ajax"/>
<script type="text/javascript">
$('#call_ajax').click(function () {
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
});
</script>
</body>
blogFunction.php
<?php
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Notice that I'm not including blogFunction.php in the index.php file! That's important.
The other way you had it, you were setting the variable to 0 each time the page loaded, which was how the function was called (if you used the console to call it).
I added a button for you to click to call the function via Ajax (per your conditions in the original question).
Hope that helps!
You need to call session_start () in your blogFunction.php file. It has to be called before any output to the brower. Probably best case would be to call it first in the script.
I think that you should first unset $_SESSION['views'] and than write again.
function blogreturn(){
$temp = $_SESSION['views'];
unset($_SESSION['views']);
$_SESSION['views'] = $temp + 1;
echo "THIS number is:" .$_SESSION['views'];
}

jQuery/PHP Hide Div, Update Information from MySQL, Show Div New Information

jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});

Categories