Cakephp ajax delete with j query - php

i've found this http://www.jamesfairhurst.co.uk/posts/view/ajax_delete_with_cakephp_and_jquery/ tutorial on the web, but it was for cakephp 1.3.
After making some adjustements to it , i try to run it, but something is going wrong. While the record gets deleted(as it should be), it refreshed the page. It's like Ajax and Jquery are not working.
Below is my code
The Controller Action
function delete($id=null) {
// set default class & message for setFlash
$class = 'flash_failure';
$msg = 'Invalid User Id';
// check id is valid
if($id!=null && is_numeric($id)) {
// get the Item
$item = $this->User->read(null,$id);
// check Item is valid
if(!empty($item)) {
$user = $this->Session->read('Auth.User');
// $exists=$this->User->find('count',array('conditions'=>array("User.username" => $user)));
if($item['User']['username']==$user['username']){
$msg = 'You cannot delete yourself!';
}
// try deleting the item
else if($this->User->delete($id)) {
$class = 'flash_success';
$msg = 'User was successfully deleted';
} else {
$msg = 'There was a problem deleting User, please try again';
}
}
}
// output JSON on AJAX request
if(/*$this->RequestHandler->isAjax()*/$this->request->is('ajax')) {
$this->autoRender = $this->layout = false;
echo json_encode(array('success'=>($class=='flash_failure') ? FALSE : TRUE,'msg'=>"<p id='flashMessage' class='{$class}'>{$msg}</p>"));
exit;
}
// set flash message & redirect
$this->Session->setFlash($msg,$class,array('class'=>$class));
$this->redirect(array('action'=>'manage'));
}
The View
<?php //view/users/manage.ctp ?>
<h1 class="ico_mug">Users</h1>
<?php echo 'Add User '.$this->Html->link($this->Html->image("add.jpg"), array('action' => 'register'), array('escape' => false));//print_r ($users); ?>
</br>
<table id="table">
<tr>
<th>ID</th>
<th>Username</th>
<th>Last Login</th>
<th>Options</th>
</tr>
<!-- Here is where we loop through our $posts array, printing out post info -->
<?php foreach ($users as $rs): ?>
<tr>
<?php echo $this->Html->script('jquery'); ?>
<td class="record">
<?php echo $rs['User']['id']; ?>
</td>
<td class="record"><?php echo $rs['User']['username']; ?></td>
<td class="record"><?php if(!$rs['User']['last_login']) {echo "Never Logged In";} else {echo $rs['User']['last_login'];} ?></td>
<td class="record"> <?php echo $this->Html->link($this->Html->image("edit.jpg"), array('action' => 'edit',$rs['User']['id']), array('escape' => false));?>
<?php
$user = $this->Session->read('Auth.User');
if($rs['User']['username']!=$user['username'])
echo $this->Html->link($this->Html->image("cancel.jpg"), array('action' => 'delete',$rs['User']['id']), array('escape' => false),array('class'=>'confirm_delete'));?>
<?php
if($rs['User']['username']!=$user['username'])
// simple HTML link with a class of 'confirm_delete'
echo $this->Js->link('Delete',array('action'=>'delete',$rs['User']['id']),array('escape' => false),array('class'=>'confirm_delete'));
?></td>
</tr>
<?php endforeach; ?>
<div class="paging">
<?php echo $this->Paginator->prev('<< ' . __('previous'), array(), null, array('class'=>'disabled'));?>
| <?php echo $this->Paginator->numbers();?>
| <?php echo $this->Paginator->next(__('next') . ' >>', array(), null, array('class' => 'disabled'));?>
</div>
</table>
<div id='ajax_loader'></div>
The Jquery
// on dom ready
$(document).ready(function(){
// class exists
if($('.confirm_delete').length) {
// add click handler
$('.confirm_delete').click(function(){
// ask for confirmation
var result = confirm('Are you sure you want to delete this?');
// show loading image
$('.ajax_loader').show();
$('#flashMessage').fadeOut();
// get parent row
var row = $(this).parents('tr');
// do ajax request
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
// hide loading image
$('.ajax_loader').hide();
// hide table row on success
if(response.success == true) {
row.fadeOut();
}
// show respsonse message
if( response.msg ) {
$('#ajax_msg').html( response.msg ).show();
} else {
$('#ajax_msg').html( "<p id='flashMessage' class='flash_bad'>An unexpected error has occured, please refresh and try again</p>" ).show();
}
}
});
}
return false;
});
}
});
Please take in mind that i'm very new to all this Jquery and Ajax thing, as well as in cakephp.
What is causing that behaviour ? (also if i try to remove the redire from the controller, i get a message that "view delete was not found" )

First of all check cookbook for HtmlHelper::link and JsHelper::link. Not sure what version of cake you have, so just switch to the right one.
The thing is - none of your Delete links has class confirm_delete (use firebug or some debugging tool) - so the link gets clicked but the javascript is never executed, that's why you get redirected.
In your case it would be:
echo $this->Html->link($this->Html->image('cancel.png'), array('controller' => 'users', 'action' => 'delete', $rs['User']['id']), array('escape'=>false, 'class'=>'confirm_delete') );
and
echo $this->Js->link('Delete', array('controller' => 'users', 'action'=>'delete', $rs['User']['id']), array('escape' => false, 'class'=>'confirm_delete'));
Then I see $('.ajax_loader').hide(); but in your view is element with id="ajax_loader", so the selector should be $('#ajax_loader').hide();
Same with $('#ajax_msg').html(, double check you have that element on page with the id="ajax_msg"
Hope it helps you further;)

Related

Internal Server Error 500 Codeigniter on upload to webhosting

I am facing server 500 error on following website, fabcoders.com/ghostwriter
Login in as username: chelsea Password:Chelsea123
once logged in you'll be directed to http://fabcoders.com/ghostwriter/dashboard page.
There you'll find a listing as topic,submission,view click the view link.
You'll be directed to http://fabcoders.com/ghostwriter/project/view_submission/230 page click the view. and that that is were i get the 500 error. It show blank but once you inspect element and go to console there you can see the error.
The code is in codeigniter
Here is the controller section
public function view_submission_detail ($submission_id)
{
$user_id = $this->session->userdata("id");
$this->load->model("submission_m");
$this->load->model("ratings_m");
$star = $this->input->post("rating");
$review=$this->input->post("reviews");
$tip=$this->input->post("tip");
$record = $this->submission_m->get($submission_id);
$rat_to=$record->fk_user_id;
//dump($record);
$select = $this->ratings_m->get($rat_to);
//$tip=$select->tip;
$this->load->model("addproject_m");
$temp = $this->user_m->get($rat_to);
$emailid = $temp->email;
$user_id = $temp->id;
$prjct = $this->addproject_m->get($record->fk_project_id);
//dump($record->fk_project_id);
//dump($prjct);
$pname = $prjct->p_title;
$buyername = $prjct->p_buyname;
$this->data['tip'] = $tip;
$this->data['numele'] = count($this->submission_m->viewusersub($user_id));
$this->data['numacc'] = count($this->submission_m->viewuseracc($user_id));
$this->data['numrej'] = count($this->submission_m->viewuserreject($user_id));
$this->data['numrew'] = count($this->submission_m->viewuserrewrite($user_id));
//$this->data['usersubs'] = $this->submission_m->viewusersub($user_id);
$get_rating_count=$this->submission_m->get_rating_count($rat_to);//rating_m
$this->data['get_rating_count']=$get_rating_count;
$get_rating_details=$this->submission_m->get_rating_details($rat_to);//rating_m
$this->data['get_rating_details']=$get_rating_details;
$sum=0;
foreach($get_rating_details as $rows)
{
$sum=$sum+$rows->rating;
}
$average_rating=0;
if($get_rating_count != 0)
$average_rating=(int)($sum/$get_rating_count);
if($this->input->post("accept") && $this->input->post("pk_submission_id")){
redirect('dashboard');
}else if($this->input->post("reject") && $this->input->post("pk_submission_id")){
$this->submission_m->reject_submission($submission_id);
$this->submission_m->rejectMail($emailid,$pname,$buyername);
redirect('dashboard');
}else if($this->input->post("rewrite") && $this->input->post("pk_submission_id")){
$this->submission_m->rewrite_submission($submission_id);
$this->submission_m->rewriteMail($emailid,$pname,$buyername);
redirect('dashboard');
}
$this->data['average_rating']=$average_rating;
$this->data['submission'] = $this->submission_m->get($submission_id);
$this->data['username'] = $this->user_m->get($this->data['submission']->fk_user_id);
$this->data['project'] = $this->addproject_m->get($this->data['submission']->fk_project_id);
$this->load->view('project/view_submission_details', $this->data);
}
Here is the view part
p_title ?>
img/close.png">
Writer's Name:
firstname ?>
Submitted Date:
created))); ?>
Rating:
</li><?php if($tip!= ""){?>
<li class="label-list">Tip for Writer:</li>
<li><?php echo $tip; } ?></li>
<br>
<?php if($numele>=1)
echo "Previous submissions";?>
<br>
<?php if($numele>=1)
echo "Number of submissions ".$numele;?>
<br>
<?php if($numacc>=1)
echo "Number of Projects Accepted ".$numacc;?>
<br>
<?php if($numrej>=1)
echo "Number of Projects Rejected ".$numrej;?>
<br>
<?php if($numrew>=1)
echo "Number of Projects Rewritten ".$numrew;?>
<br>
<? } ?>
<?php //echo "Tip".$get_rating_details->tip ?>
</ul>
<div class="content1 div-center2 colorwhite">
<p class="text-content"><?php echo nl2br( htmlentities($submission->content)) ?></p>
</div>
<div class="buttons">
<ul class="button-row">
<?php if(!($project->p_complete==1) && ($submission->status=='NOT REVIEWED')) { ?>
<?php
echo form_open('','id="contentForm"');
echo form_hidden("pk_submission_id",$submission->pk_submission_id);
echo " ".form_submit("accept","Accept",'class="btn-green .btn-small" id="acceptBtn"');
echo " ".form_submit("reject","Reject",'class="btn-red .btn-small"');
echo " ".form_submit("rewrite","Rewrite",'class="btn-blue .btn-small"');
echo form_close();
?>
<?php } ?>
</ul>
</body>
</html>
<script>
$(function() {
$("#acceptBtn").click(function(e){
var sdata = $('#contentForm').serialize();
$.ajax({
url: "<?php echo site_url('project/accept_submission'); ?>",
type: "POST",
data:sdata +'&accept=1',
success: function(data){
$('.buttons').remove();
$('#baseModal-xs .modal-content').html(data);
$('#baseModal-xs').modal("show");
}
});
return false;
});
});
</script>
It works locally but it does not run when live the project is still in development stage.
I don't know much about servers cause i only do coding, but in my company i was told to fix the issue and i have no clue my week end is going to be ruined :(
I had previously posted regarding the same issue but it was for different section even that was not fixed.
I don't know if the model part also can cause issue but i cant put the code cause i have passed to limit of the question size
In the view part i had added a extra closing brace which had no opening brace i removed that brace and Wa-lah it worked :).

Prevent from editing record directly hitting url in cake php

How to prevent user from hitting url directly in browser so that he can't edit record like this:
http://localhost/demo_cake/users/edit/7
My edit code in controller is as given below, Please give any suggestions:
public function edit() {
$id = $this->request->params['pass'][0];
$this->User->id = $id;
if( $this->User->exists() ){
if( $this->request->is( 'post' ) || $this->request->is( 'put' ) ){
if( $this->User->save( $this->request->data ) ){
$this->Session->setFlash('User was edited.');
$this->redirect(array('action' => 'index'));
}else{
$this->Session->setFlash('Unable to edit user. Please, try again.');
}
}else{
$this->request->data = $this->User->read();
}
}else{
$this->Session->setFlash('The user you are trying to edit does not exist.');
$this->redirect(array('action' => 'index'));
}
}
index.php
<h2>Users</h2>
<!-- link to add new users page -->
<div class='upper-right-opt'>
<?php echo $this->Html->link( '+ New User', array( 'action' => 'add' ) ); ?>
</div>
<table style='padding:5px;'>
<!-- table heading -->
<tr style='background-color:#fff;'>
<th>ID</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Username</th>
<th>Email</th>
<th>Actions</th>
</tr>
<?php
//loop to show all retrieved records
foreach( $users as $user ){
echo "<tr>";
echo "<td>{$user['User']['id']}</td>";
echo "<td>{$user['User']['firstname']}</td>";
echo "<td>{$user['User']['lastname']}</td>";
echo "<td>{$user['User']['username']}</td>";
echo "<td>{$user['User']['email']}</td>";
//here are the links to edit and delete actions
echo "<td class='actions'>";
echo $this->Html->link( 'Edit', array('action' => 'edit', $user['User']['id']) );
//in cakephp 2.0, we won't use get request for deleting records
//we use post request (for security purposes)
echo $this->Form->postLink( 'Delete', array(
'action' => 'delete',
$user['User']['id']), array(
'confirm'=>'Are you sure you want to delete that user?' ) );
echo "</td>";
echo "</tr>";
}
?>
</table>
Normally you would check if the session's user id is the same user id of the record he is trying to change or if the session's user id has enough privileges to do so to other users.
something like this
<button type="submit" name="cmd_edit" value="id_here">Edit</button>
You should use your own isAuthorized(user=null){} function and check if the user has the sufficient rights do fulfill this Operation. Have a look at Authorization (who’s allowed to access what).

CakePHP pagination not working beyond 1st page

I have a view in my site that has two divs. one houses a search box and the other is where the result of the search is shown. by default, nothing is loaded on the result div. only when there is a search via post request, the result div is populated. However, this is causing problem with the pagination functionality as the second time the page loads, it doesnt have the data to go around with listing the rest of the results. How can i modify my controller/view to meet this need?
My action in the controller:
public function search(){
if($this->request->is('post')){
if($this->request->data['User']['search']!=null){
$search_name=$this->request->data['User']['search'];
$this->Paginator->settings = array(
'conditions'=>array('User.name LIKE'=>'%'.$search_name.'%'),
'order' => array('User.datetime' => 'desc'),
'limit' => 10
);
$feed = $this->Paginator->paginate('User');
$this->set('search_result',$feed);
}
else{
$this->Session->setFlash(__("Cant make an empty search"));
return $this->redirect(array('action'=>'search'));
}
}
}
My View:
<?php
include 'header.ctp';
echo '<div id="feed">';
echo $this->Form->create(null, array('url' => array('controller' => 'users', 'action' => 'search')));
echo $this->Form->input('search');
echo $this->Form->end('Search');
echo 'search by name';
echo '</div>';
if(isset($search_result)){
echo '<div id="tweet_records">';
if(!empty($search_result)){
foreach ($search_result as $user) :
$formatted_text;
$latest_tweet_time;
$formatted_time;
if(!empty($user['Tweet'])){
$formatted_text=$this->Text->autoLinkUrls($user['Tweet']['0']['tweet']);
$latest_tweet_time=$user['Tweet']['0']['datetime'];
$formatted_time;
if(strlen($latest_tweet_time)!=0){
$formatted_time='Tweeted at '.$latest_tweet_time;
}
else{
$formatted_time='No tweets yet';
}
}
else if(empty($user['Tweet'])){
$formatted_text='No tweets yet';
$formatted_time='';
}
echo '<table id="t01">';
echo'<tr>';
echo '<td>'.
$user['User']['name'].'#'.$this->HTML->link($user['User']['username'], array('controller'=>'tweets','action'=>'profile',$user['User']['id'])).'<br>'.$formatted_text.' '.'<br>'.'<font color="blue">'.$formatted_time.'</font>';
echo '<div id="delete">';
$selector='true';
foreach ($user['Follower'] as $follower) :
if($follower['follower_user_id']==AuthComponent::user('id')){
$selector='false';
echo $this->Form->postlink('Unfollow',array('controller'=>'followers','action'=>'unfollow',$user['User']['id']),array('confirm'=>'Do you really want to unfollow this person?'));
}
endforeach;
if($selector=='true' & $user['User']['id']!=AuthComponent::user('id')){
echo $this->Form->postlink('Follow',array('controller'=>'followers','action'=>'follow',$user['User']['id']));
}
echo '</div>';
echo '</td>';
echo '</tr>';
endforeach;
echo'</table>';
echo 'Pages: ';
echo $this->Paginator->prev(
' < ',
array(),
null,
array('class' => 'prev disabled')
);
echo $this->Paginator->numbers();
echo $this->Paginator->next(
' > ' ,
array(),
null,
array('class' => 'next disabled')
);
}
else{
echo '<font color="red"> No results found </font>';
}
echo '</div>';
}
You are searching for results only on post request. But when you press the next button you are making a get request. So the first if statement doen't return true so you are not passing any data to your view.
Even if you remove the first if statement for post you'll still won't see any data because the next button doesn't post any data to make true the second statement.
PS:
On CakePHP include is not a preferable thing to do. Also you haven't mentioned the version you are using.

PHP, Requesting from link and echoing json array

I have this code but it does not seem to be working. After entering an IP into the text field and hitting the button it will return with the page loaded up to the php code but will not load the php code result nor any code past it.
<?php
if(isset($_POST['resolve'])){
$api = "https://iphub.p.mashape.com/api.php?ip=";
$endbit = "&showtype=4";
if(strlen($_POST['name'])==0){
echo "fill in all fields!";
} else {
// assuming $_POST['resolve'] has an IP
// $response = file_get_contents($api.$_POST['name'].$endbit);
$response = Unirest\Request::get($api.$_POST['name'].$endbit,
array(
"X-Mashape-Key" => "U3sk6nAZzBmshyiHEUZHigxLGp1ZTZnKjsnkd8LWULJmRRp",
"Accept" => "application/json"
)
);
?>
<div align="center">
<?php
if($response['proxy'] == '0') {
echo 'No';
}
elseif($response['proxy'] == '1') {
echo 'Yes';
}
else {
echo 'Error.';
}
?>
</div>
<?php
}
}
?>
The API I am using requires me to have the header/X-Mashape-Key.

Help creating an ajax method to add to basket

I have the following code that I want to turn into a silent ajax function so the page does not need to refresh, when a user adds a product the basket.
Currently I have the following code,
PHP
function showProduct($productId)
{
if (!$productId > 0)
{
redirect('home');
}
$this->load->model('Product_model');
$this->load->model('Checkout_model');
$this->data['items'] = $this->Checkout_model->GetProducts();
// Check to see if the Add To Bag button has been clicked.
if ($this->input->post('btnAddToBag'))
{
$derivativeId = $this->input->post('selDerivative-1');
$quantity = $this->input->post('selQuantity');
$derivative = $this->Product_model->GetProducts(array('pdId' => $derivativeId), 'small');
// Add item to shopping bag.
$attributes = $this->Product_model->GetProductDerivatives(array('pdId' => $derivativeId));
$this->Checkout_model->AddProduct($derivative, $attributes, $quantity);
$this->data['message'] = 'Item added to Shopping Bag.';
// Update Delivery Price
$this->Checkout_model->updateDelivery(49);
//get the bag details
}
$this->data["product_details"] = $this->Product_model->GetProducts(array('productId' => $productId, 'pdOrdering' => 1), 'detail');
$this->data['product_images'] = $this->Product_model->GetProductImages(array('productId' => $productId, 'ipPosition' => 'detail'));
//send the new filename to the view
//die(print_r($this->data['product_images']));
//die(print_r($this->data['sliderUrl']));
// Retrieve images for initial derivative.
$this->load->model('Attribute_model');
$this->data['derivative_images'] = $this->Attribute_model->GetAttributeValues(array('pdavProductDerivativeId' => $this->data["product_details"]->pdId), 'small', TRUE);;
$derivatives = $this->Product_model->GetProductDerivatives(array('pdProductId' => $productId));
$this->data["product_derivatives"] = $derivatives['derivatives'];
$this->data["product_attribute_names"] = $derivatives['attributeNames'];
// Retrieve details of this range.
$subRangeId = $this->data["product_details"]->productRangeId;
$this->data["sub_range_details"] = $this->Range_model->GetRanges(array('range.rangeId' => $subRangeId));
$rangeId = $this->data["sub_range_details"]->rangeParentId;
$this->data['active_menu_item'] = "subrange";
if ($rangeId == 0)
{
$rangeId = $subRangeId;
$this->data['active_menu_item'] = "full";
}
$this->data["range_details"] = $this->Range_model->GetRanges(array('range.rangeId' => $rangeId, 'range.rangeParentId' => 0), 'navigation');
if ($rangeId != $subRangeId)
$this->template->set_breadcrumb($this->data["range_details"]->rangeTitle, $this->data["range_details"]->rangePath);
//$this->data["rangePath"] = $this->uri->segment(1).'/';
$this->data["rangeId"] = $rangeId;
$this->data["subRangeId"] = $subRangeId;
// Retrieve list of sub ranges in this range.
$this->data["sub_ranges"] = $this->Range_model->GetRanges(array('range.rangeParentId' => $rangeId));
$this->data["individual_products"] = $this->Product_model->GetProducts(array('psiParentId' => $productId), 'small');
$this->data["related_products"] = $this->Product_model->GetRelatedProducts(array('product_related.prProductId' => $productId, 'ordering' => 'productActualPrice'), 'small');
$this->data['bestsellers'] = $this->Product_model->GetProducts(array('productBestSeller' => '1', 'range.rangeParentId' => $rangeId, 'ordering' => 'range.rangeOrder'), 'small');
$this->data["multibuy"] = $this->Product_model->GetProducts(array('psi.psiChildId' => $productId, 'productSavingType' => 'multi-buy'));
//$this->load->view('collection', $data);
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") {
$this->template
->build('product/quickview', $this->data); // views/product/product.php
}else{
$this->template
->set_layout('default') // application/views/layouts/default.php
->title(($this->data["product_details"]->productMetadataTitle != '' ? $this->data["product_details"]->productMetadataTitle : $this->data["product_details"]->productTitle))
->set_metadata('keywords', $this->data["product_details"]->productMetadataKeywords, 'meta')
->set_metadata('description', ($this->data["product_details"]->productMetadataDescription != '' ? $this->data["product_details"]->productMetadataDescription : $this->data["product_details"]->productShortDesc), 'meta')
->set_metadata('', site_url('assets/js/product.js'), 'js')
->set_metadata('', site_url('assets/js/jquery.nivo.slider.js'), 'js')
->set_metadata('', site_url('assets/js/slider.js'), 'js')
->set_partial('left-nav', 'blocks/ranges_sub_menu') // application/views/blocks/ranges_sub_menu.php
->set_breadcrumb($this->data["sub_range_details"]->rangeTitle, $this->data["sub_range_details"]->fullRangePath)
->set_breadcrumb($this->data["product_details"]->productTitle, $this->data["product_details"]->fullProductPath)
->build('product/product', $this->data); // views/product/product.php
}
}
HTML FORM
<?php echo form_open(current_url(), array('id' => 'frmProducts'), array('submitted' => '1')); ?>
<div class="formRow">
<label for="rattanType"><?php echo $product_attribute_names; ?> </label><br />
<?php
$options = array();
foreach ($product_derivatives as $derivative) :
$options[$derivative['derivativeId']] = $derivative['attributeValues'];
endforeach;
?>
<?php echo form_dropdown('selDerivative-1', $options, $product_details->pdId, 'class="select clear" id="selDerivative-1"'); ?>
</div>
<?php if (count($individual_products) > 0) : ?>
<div class="formRow">
<label for="itemType">Item</label><br />
<select class="select clear" id="selURL-1" name="selURL-1">
<option value="<?php echo current_url(); ?>">Full Set</option>
<?php foreach ($individual_products as $product) : ?>
<option value="<?php echo site_url($product->fullProductPath); ?>"><?php echo $product->productTitle; ?> - £<?php echo ($product->productSavingType != 'none' ? $product->productSavingPrice : $product->productPrice); ?></option>
<?php endforeach; ?>
</select>
<input id="btnGo-1" name="btnGo-1" type="submit" value="GO" />
</div>
<?php endif; ?>
<div class="formRow">
<label for="addQty">Quantity</label><br />
<?php
$options = array();
for ($i = 1; $i < 10; $i++) :
$options[$i] = $i;
endfor;
?>
<?php echo form_dropdown('selQuantity', $options, '1', 'class="small select clear"'); ?>
</div>
<input type="submit" value="add to bag" name="btnAddToBag" id="btnAddToBag" />
<?php echo form_close(); ?>
// Reset action of form when add to bag button is clicked.
$("#btnAddToBag").click(function () {
$("#frmProducts").attr("action","<?php echo current_url(); ?>");
});
How can I change this code that it makes an ajax request and updates the cart without refreshing the page?
You need to split off your basket display into another file so that you can use:
$.load()
Example basic usage:
$('#ShoppingCart').load('Cart.php', function() {
alert('Load was performed.');
});
<div id="ShoppingCart"> </div>
Or a little more like youve currently got it set up:
$("#btnAddToBag").click(function () {
$('#ShoppingCart').load('Cart.php', function() {
alert('Load was performed.');
});
});
Edit:
Re-reading your post, do you not want the cart to update atall?
In that case you would need to use $.post()
See: http://api.jquery.com/jQuery.post/
I have already answered a question for JSP/SERVLET here this one should work by changing the URL to a PHP page...
You need to make an XML Http request to the Servlet for that you need to make a XML Http object in the javascript in your HTML/PHP page
var myxmlhttpobj=new GetXmlHttpObject();
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
Now you need to make a request to the PHP from the javascript
var url="urlofPHPpage";
var para="parmeter1=value1&parameter2=valu2;
myxmlhttpobj.open("POST",url,true);
myxmlhttpobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myxmlhttpobj.setRequestHeader("Content-length", para.length);
myxmlhttpobj.setRequestHeader("Connection", "close");
myxmlhttpobj.onreadystatechange=ajaxComplete;
myxmlhttpobj.send(para);
At the PHP page you need to process the result and sent it back as string:
When the request comes back the myxmlhttpobj.onreadystatechange=ajaxComplete; will be called
function ajaxComplete(){
if(myxmlhttpobj.readyState==4){
///Display the result on the HTML/PHP Page BASKET
}
}
That should help...
Also have a look at jQuery Ajax API.

Categories