WP Ajax not working in else condition - php

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.

Related

Change the button text after the ajax update db

I'm trying to learn php and WP developing. My goal is to mark posts done/read on button click. I found this great ajax tutorial plugin. Here is the link of the tutorial, and for the plugin. I have successfully manage to edit the plugin form my needs. On click it checks if there is already that id in the array, if it is it deletes that element from the array. If there is not id in the array, or the array is empty it adds post id into the array. Afterwards the array is updated into db.
Here is the code for the button, that is added after the post content:
public function rml_button( $content ) {
$rml_post_id = get_the_id();
// Show read me later link only when user is logged in
if( is_user_logged_in() && get_post_type() == post ) {
if( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
$value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
}
if( $value ) {
if (in_array($rml_post_id, $value)) {
$html .= 'DONE';
$content .= $html;
}
else {
$html .= 'MARK AS DONE';
$content .= $html;
}
}
else {
$html .= 'MARK AS DONE';
$content .= $html;
}
}
return $content;
}
Here is the code for updating the db:
public function read_me_later() {
check_ajax_referer( 'rml-nonce', 'security' );
$rml_post_id = $_POST['post_id'];
$echo = array();
if( get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true ) !== null ) {
$value = get_user_meta( wp_get_current_user()->ID, 'rml_post_ids', true );
}
if( $value ) {
if (in_array($rml_post_id, $value)) {
foreach (array_keys($value, $rml_post_id, true) as $key) {
unset($value[$key]);
}
$echo = $value;
}
else {
$echo = $value;
array_push( $echo, $rml_post_id );
}
}
else {
$echo = array( $rml_post_id );
}
update_user_meta( wp_get_current_user()->ID, 'rml_post_ids', $echo );
// Always die in functions echoing Ajax content
die();
}
Finally, here is the .js for the ajax call:
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'id' );
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
data : {
action : 'read_me_later',
security : rml_obj.check_nonce,
post_id : rml_post_id
},
success : function( response ) {
jQuery('.rml_contents').html(response);
}
});
//jQuery(this).hide();
});
});
What I cannot figure out, and sorry if it is a stupid question, is how to change button text after the ajax? From "MARK AS DONE" to "DONE" and vice versa. How to call this function rml_button(), inside read_me_later() so that button text will be changed after the db update.
Thank you.
Added if else statements inside ajax success function to be able to change a tag text from MARK AS DONE to DONE and vice versa.
Try:
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 'id' );
var ts = jQuery(this);
jQuery.ajax({
url : rml_obj.ajax_url,
type : 'post',
data : {
action : 'read_me_later',
security : rml_obj.check_nonce,
post_id : rml_post_id
},
success : function( response ) {
if(ts.html()=="DONE") { ts.html("MARK AS DONE"); } // ts.html()=="DONE" - maybe changed based on response
else { ts.html("DONE"); }
jQuery('.rml_contents').html(response);
}
});
//jQuery(this).hide();
});
});

Magento : How to display selected custom option price in product detail page In price box

I want to display custom option price with name in price box in product detail page.
I also try this link but not getting success this is link i use
So please suggest me any solution.
first of all you have to put button calculateprice
then onclick of calculateprice you have to call function chkprice()
function chkpice()
{
var a=document.getElementById("options_1_text").value;
var b=document.getElementById("options_2_text").value;
var c=document.getElementById("options_3_text").value;
var d=document.getElementById("options_4_text").value;
var e=<?php echo $_product = $this->getProduct()->getPrice()?>;
var f=(a+b+c+d)+e;
var e=document.getElementById(('product-price-'+<?php echo $_product = $this->getProduct()->getId()?>)).innerHTML;
$('product-price-'+<?php echo $_product = $this->getProduct()->getId()?>).innerHTML =''+e.replace(<?php echo $_product = $this->getProduct()->getPrice()?>,d)+'</span>';
}
insted of options_1_text,options_2_text,options_3_text,options_4_text put your id it will get your result
First you do the function that takes care of updating the charges:
function updateCharges(){
var tmpText="";
$("input[type='select']").each(function{
tmpText+=$("#"+this.id+"option:selected").text()+"<br>";
});
$("#detailDiv").html(tmpText)
}
Then you just bind the selects to that function
$("input[type='select']").change(updateCharges)
Now you just have to make sure to include in your template a <div id="detailDiv"></div>
I would just create a custom block with the above code and place it inside the product detail page. Also you should check the selectors used, they will look for absolutelty ALL selects on the page, so thats not what you may want. But its just a matter of firebug-ging untill the aproppiate selector is found
Recently I need something similar. Perhaps it is helpful for you.
Block class:
class Foo_Bar_Block_Baz extends Mage_Catalog_Block_Product_View {
protected function getOptionDataCollection($options) {
$optionDataCollection = array();
foreach ($options as $option) {
$optionDataCollection[$option->getData('option_id')] = array_filter($option->getData());
}
return $optionDataCollection;
}
protected function getOptionValueDataCollection($options) {
$optionValueDataCollection = array();
foreach ($options as $option) {
$optionType = $option->getType();
if ($optionType == 'drop_down') {
$optionValues = $option->getValues();
foreach ($optionValues as $valueItem) {
// here you could also use the option_type_id (in my case I needed the sku)
$optionValueDataCollection[$valueItem->getData('sku')] = array_filter($valueItem->getData());
}
} else {
//Mage::throwException('Unexpected input. Processing for this optionType is not implemented');
}
}
return $optionValueDataCollection;
}
public function getOptionsJson() {
$data = array(
'options' => array(),
'optionValues' => array()
);
$options = $this->getProduct()->getOptions();
array_push($data['options'], $this->getOptionDataCollection($options));
array_push($data['optionValues'], $this->getOptionValueDataCollection($options));
$optionsJson = json_encode($data);
return $optionsJson;
}
}
Template
<script id="optionsJson" type="application/json">
<?php echo $this->getOptionsJson(); ?>
</script>
JS
var json = JSON.parse(document.getElementById("optionsJson").innerHTML),
options = json.options[0],
optionValues = json.optionValues[0];
optionValues['<optionValueSKU>'].default_title
optionValues['<optionValueSKU>'].price
-----------Create controller-------------
<?php
class Magento_Guys_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
echo "Thank you !";
}
public function genCartAction()
{
$id = $this->getRequest()->getParam('pid');
$_product = Mage::getModel('catalog/product')->load($id);
$buy = Mage::helper('checkout/cart')->getAddUrl($_product);
echo $qty = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
//echo $id;
//echo $this->getRequest()->getParam('id');;
}
}
?>
----------------Change Add to cart code-------------------
<?php if ($_product->isAvailable()): ?>
<b class="available_quanity" style="display: none">Available Quantity :</b> <span id="simplestock" class="simplestock">Please select a color to view the quantity</span>
<?php endif; ?>
</div>
<?php if(!$_product->isGrouped()): ?>
<div class="qty">
<label for="qty"><?php echo $this->__('Qty:') ?></label>
<?php $i = 0; ?>
<select id="qty" class="input-text" name="qty" style="width:50px;">
<?php while($i<=(int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()):?>
<option value="<?php echo $i; ?>"><?php echo $i++; ?></option>
<?php endwhile; ?>
</select>
</div>
<?php endif; ?>
----------------Add Ajax for get Quantity---------------
<script>
jQuery(document).ready(function() {
jQuery(".product-options select[id^='attribute']").on('change', function() {
var id = getSimpleProductId();
var qty = "";
jQuery('.available_quanity').show();
jQuery("#fancybox-loading").show();
jQuery.ajax({
type: "POST",
data: 'pid=' + id,
url:'https://www.thewirelesscircle.com/guys/index/genCart',
success:function(response){
if (response) {
qty = response;
var x = document.getElementById("qty");
var i;
removeOptions(x);
for(i=1;i<=qty;i++) {
var option = document.createElement("option");
option.text = i;
option.value = i;
x.add(option);
}
}
jQuery("#fancybox-loading").hide();
}
});
});
});
</script>
---------------Get Selected Option Id in Magento-------------------
<script type="text/javascript">
function removeOptions(selectbox)
{
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--)
{
selectbox.remove(i);
}
}
function getSimpleProductId() {
var productCandidates = [];
jQuery.each(spConfig.settings, function (selectIndex, select) {
var attributeId = select.id.replace('attribute', '');
var selectedValue = select.options[select.selectedIndex].value;
jQuery.each(spConfig.config.attributes[attributeId].options, function(optionIndex, option) {
if (option.id == selectedValue) {
var optionProducts = option.products;
if (productCandidates.length == 0) {
productCandidates = optionProducts;
} else {
var productIntersection = [];
jQuery.each(optionProducts, function (productIndex, productId) {
if (productCandidates.indexOf(productId) > -1) {
productIntersection.push(productId);
}
});
productCandidates = productIntersection;
}
}
});
});
return (productCandidates.length == 1) ? productCandidates[0] : null;
}
</script>
Open page: app\code\core\Mage\Catalog\Block\Product\View\Options.php find protected function _getPriceConfiguration($option) function and add $data['title'] = $option->getTitle(); before return $data; statement.
Now, open app\design\frontend\YOUT_TEMPLATE_PATH\default\template\catalog\product\view\options.phtml
Add <div id="optiontitle"></div> top of the page.
Then find this:
$A(element.options).each(function(selectOption){
if ('selected' in selectOption && selectOption.selected) {
if (typeof(configOptions[selectOption.value]) != 'undefined') {
curConfig = configOptions[selectOption.value];
}
}
});
Replace by:
$A(element.options).each(function(selectOption){
if ('selected' in selectOption && selectOption.selected) {
if (typeof(configOptions[selectOption.value]) != 'undefined') {
curConfig = configOptions[selectOption.value];
optionTitle = curConfig.title + "<br>";
$("optiontitle").insert(optionTitle);
}
}
});

Echo jQuery loop using 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 }
}
}
?>

CKEditor with json not passing content

I am trying to submit a form without leaving the page using json.
However, the method below ignores the data I have entered into the CKEditor.
Any ideas (and feel free to correct my terminology)?
<script type="text/javascript">
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
</script>
<form name="addStory" action="" method="post" id="addStory">
<label for="story_story">Story: </label><textarea id="story_story" name="story_story"><p></p></textarea>
<?php
// Include the CKEditor class.
include("ckeditor/ckeditor.php");
// Create a class instance.
$CKEditor = new CKEditor();
$CKEditor->basePath = '/ckeditor/'
$CKEditor->replace("story_story");
?>
<input type="submit" value="Submit" />
</form>
_posteddata.php:
include 'connection.php';
function check_input($value, $quoteIt)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (is_null($value) || $value=="") {
$value = 'NULL';
} else if (!is_numeric($value) && $quoteIt == 1) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// CKEDITOR STUFF FOR STORY_STORY
if (isset($_POST)) {
$postArray = &$_POST;
}
foreach ( $postArray as $sForm => $value )
{
if($sForm == "story_story") {
$story_story = check_input($value, 1);
}
}
$query = "INSERT INTO story_table (story) VALUES ($story_story)";
mysql_query($query) or die(mysql_error() . $query);
$return = array();
$return['adminList'] = "New story added with ID: " . mysql_insert_id();
header('application/json');
echo json_encode($return);
mysql_close();
In this kind of situation you must force CKEditor to update the contents of the textarea
So your function would be something like this:
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
CKEDITOR.instances.story_story.updateElement(); // Update the textarea
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});

passing params through ajax to php

I know this is a very basic question, but i couldnt figure how to fix the code even after crawling the web for past 1 hour.
I have an unordered list containing the information about the categories in the database, with cat_id as primary key. and a subject table with cat_id as its foreign key, so i want to access the subjects table through ajax request for given category ID. below is the code i used to generate categories. Where i am stuck is, i dont know which DOM element to fetch in order to send the unique id in the url parameter ..
thanks ..
<ul id="search_form">
<?php
$cat = Category::find_all();
foreach($cat as $category) {
echo '<li id="';
echo $category->cat_id;
echo '"><a href="subject.php?id=';
echo $category->cat_id;
echo'">';
echo $category->category;
echo '</a></li>';
}
?>
</ul>
<div id="results">
<!-- ajax contents goes here -->
</div>
the ajax file is
window.onload = init;
function init() {
if (ajax) {
if (document.getElementById('results')) {
document.getElementById('search_form').onclick = function() {
ajax.open('get', 'subject.php?id='+id ); // subject.php?id=
// how will i pass the variable
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
}
}
function handleResponse(ajax) {
if (ajax.readyState == 4) {
if ((ajax.status == 200) || (ajax.status == 304) ) {
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
results.style.display = 'block';
}
}
}
and the subject.php
<?php
//include("tpl/header.php");
include("includes/initialize.php");
?>
<h2></h2>
<?php
if (isset($_GET['id'])) {
$id= mysql_real_escape_string($_GET['id']);
$subject = Subject::find_subject_for_category($id);
foreach($subject as $subj) {
echo $subj->subject_title;
}
} else {
echo "No ID Provided";
}
?>
I have used Jquery to do these kind of things and it works fine for me.
$.ajax({
type: GET,
url: "subject.php",
data: {id: $('#search_form :selected').val()},
success: function(result){
// callback function
}
});

Categories