Prototype Ajax in magento - javascript

I have updated a stock value for product on button click, I want to change my ajax code to magento prototype ajax.
My code :
<tr>
<input type="hidden" class="product_id" id="product_id" value="<?php echo $_obj->getId() ?>"/>
<td><?php echo $_obj->getId() ?></td>
<td><span class="nobr"><?php echo $_obj->getName(); ?></span></td>
<td id="stock-qty<?php echo $_obj->getId() ?>"><?php echo round($_obj->getQty()); ?></td>
<td><span class="nobr"><input type="text" name="update-stock" id="update-stock" value="<?php echo round($_obj->getQty()); ?>" class="update-stock validate-number"/>
<button type="submit" name="stockupdate" class="stockupdate" value="Submit">Update</button>
</td>
My ajax code is:
jQuery('.stockupdate').click(function() {
jQuery('#loading-mask').show();
var update_stock = jQuery(this).parents('tr').find('.update-stock').val();
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var product_id = jQuery(this).parents('tr').find('.product_id').val();
var url = "<?php echo Mage::getUrl('marketplace/vendor/stockupdate'); ?>";
jQuery('.success-message').html('');
if(update_stock!="" && numberRegex.test(update_stock)) {
jQuery.ajax({
type: "POST",
data: ({updatestock: update_stock , product_id: product_id}),
url: url,
success: function (result) {
jQuery('.success-message').html('');
if(result != 'null'){
jQuery('#loading-mask').hide();
jQuery('#stock-qty'+product_id).text(result);
var message = "<div class='success-message' style='color:green;'>Updated Successfully.</div>";
jQuery('#stock-qty'+product_id).next('td').find('.update-stock').after(message);
}
}
});
}else{
var message = "<div class='success-message' style='color:red;'>Please enter the number.</div>";
jQuery('#stock-qty'+product_id).next('td').find('.update-stock').after(message);
}
})
Now I want to change this ajax to prototype ajax. but i am not able to do.
My prototype ajax:
function SubmitRequest()
{
var update_stock = jQuery(this).parents('tr').find('.update-stock').val();
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var product_id = jQuery(this).parents('tr').find('.product_id').val();
var url = "<?php echo Mage::getUrl('marketplace/vendor/stockupdate'); ?>";
jQuery('.success-message').html('');
if(update_stock!="" && numberRegex.test(update_stock)) {
new Ajax.Request(url, {
method: 'POST',
parameters: ({updatestock: update_stock , product_id: product_id}),
onSuccess: successFunc,
onFailure: failureFunc
});
}
}
function successFunc(response){
alert(response);
if (200 == response.status){
alert("Call is success");
}
var container = $('notice');
var content = response.responseText;
container.update(content);
}
function failureFunc(response){
alert("Call is failed" );
}
Can anyone help me?
Thanks in advance

Related

Removing cart products from input with product id value

I wanted to work with input type ="hidden" so I can do a check. I have a slider which displays products of a category and through two Ajax requests I add and remove them through clicks on buy and remove buttons, however that does not have as much relevance in this question.
Only one such product on the slide can be purchased by order, but if one of them is added and the page is updated and the buy button is clicked again, another of that product is added, which should not happen. I wanted to make sure that in the update of the page, if there is already one of these products added, it is removed, but I do not know where to follow it to complete it.I think I should use an input type ="hidden", so that through it I can save the value of the id of the added product, but I do not know how to do this verification.
Below I will add the code of the buttons and the input that I have already made and are correct, besides the code of the Ajax requisitions. If necessary, I add the code of the controllers I use.
Button and input code:
<button style="margin-left: 11%;" type="button" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none; margin-left: 11%;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remove</span></span></button>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="" />
Ajax requisition code:
var productSelected = "";
function addCartao(product){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId);
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
What you should do is make a small php code to do the verification, where it contains the SKUs of these products and if they are in the cart, assign a value to a boolean variable and insert it into an input to work this value in jQuery.
Php code for verification:
<?php
$array_de_skus_de_cartoes = array(45,60,80,90,102,103,104,105); //SKUs of products
$isCartaoAdicionado = 0;
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
foreach ($array_de_skus_de_cartoes as $sku) {
if($sku == $item->getProduct()->getSku()) {
$isCartaoAdicionado = 1;
$cartao_id = Mage::getModel("catalog/product")->getIdBySku($sku);
}
}
}
if($isCartaoAdicionado == 1) {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="1" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="<?php echo $cartao_id ?>" />
<?php
}
else {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="0" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="" />
<?php
}
?>
Ajax request code updated:
var isCartaoAdicionado = $j('#cartao_adicionado').val();
var isCartaoAdicionadoProductId = $j('#cartao_adicionado_product_id').val();
var productSelected = "";
function addCartao(product){
if(isCartaoAdicionado == 1){
removeCartaotoCart(isCartaoAdicionadoProductId);
}
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado'+product).val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId); $j('#cartaoMensagemAdicionado'+itemId).val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}

Delete record using jquery and ajax

When I am using this code it goes in success else condition and show error. But when I refresh the page the record is deleted automatically.
Please suggest me what I can do.
jquery script:
<script>
$(document).ready(function(){
$(".delete").click(function(event){
alert("Delete?");
var href = $(this).attr("href")
var btn = $(this);
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
event.preventDefault();
})
});
</script>
View file:
<table style="width:100%" border="1" class="table">
<thead>
<tr>
<th>score Id</th>
<th>student name </th>
<th>subject Name</th>
<th>student marks</th>
<th>Action</th>
</tr>
</thead>
<?php foreach($score as $r): ?>
<tbody>
<tr><td><?php echo $r->score_id; ?></td>
<td><?php echo $r->student_name; ?></td>
<td><?php echo $r->subject_name; ?></td>
<td><?php echo $r->marks; ?></td>
<?php if($status <> 1): ?>
<?php if($admin_id == $r->admin_id): ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>"> Delete</a></td>
<?php endif; ?>
<?php else: ?>
<td><a class="btn btn-info" href="<?php echo base_url(); ?>index.php/score_listing/edit/<?php echo $r->score_id; ?>" > Edit</a><a class="btn delete btn-danger" href="<?php echo base_url(); ?>index.php/score_listing/delete/<?php echo $r->score_id; ?>" > Delete</a></td>
<?php endif; ?>
</tr>
</tbody>
<?php endforeach; ?>
</table>
Controller file:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = array('error' => 'Error while deleting record');;
return json_encode(array("success" => true));
}
Just change your controller function's last line:
return json_encode(array("success" => true));
to
echo 'Success';
update you controller function as,
public function delete($id) {
...
...
die('Success');
}
I just tried the below condition in script for ajax and it works. I think I am not confirming or not taking response so thats why it continuously going into else condition where error is written.
Hope this will help some one.
MY new script
<script>
$(document).ready(function(){
$(".delete").click(function(event){
var del = confirm("Delete record?");
var href = $(this).attr("href")
var btn = $(this);
if(del == true)
{
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response != "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
}
event.preventDefault();
})
});
</script>
Your ajax return an object so you cant use if (response == "Success") like this.
change code like this:
public function delete($id)
{
$admin_name = $this->session->userdata('admin_name');
log_message('debug',"this record deleted by Admin = ".$admin_name );
$score = $this->score->delete_operation($id);
$error_data = 2;
echo 1;
}
if it's true it return 1, so chage ajax like this:
if (parseInt(response)==1)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
I assumed you want hide tr if response is true.
Because you passed it as an array (in javascript it will be converted as an object), the value of the response will be available as response.success. You can check the response object if you write it to the console.
Try this in your ajax method:
success: function(response) {
console.log(response);
if (response.success == true)
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
EDIT:
And I suggest you to change the output in your controller's method:
$this->output->set_content_type('application/json')->set_output(json_encode(array("result" => true)));
instead of
return json_encode(array("success" => true));

ajax on update data in database using codeigniter

<button id="survey_act" method="post" class="tiny ui blue button" type="button" value="<?php echo $surv['id']; ?>" >Activate Survey</button>
This is my button on click -
<script>
$(document).ready(function(){
$(document).on("click","#survey_act", function(){
alert(this.value);
idx = this.value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/admin/survey/act_surveyby_id/')?>/"+idx,
}).done(function(msg){
if(msg=="success"){
alert('You Successfully Activated the Survey!');
}
});
});
});
</script>
This is my javascript -
public function act_surveyby_id($id){
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id)){
echo "success";
}else{
echo "invalid";
}
}
This is my controller -
public function insert_activate($id){
$date = date('m-d-Y',now());
$stat = 'Active';
$data = array(
'issued_date' => $date ,
'status' => $stat
);
$this->db->update('survey', $data)->where('survey_id', $id);
if($this->db->affected_rows()>0){
return true;
}else{
return false;
}
}
}
This is my model -
Problem: when i click the activate survey it wont change/update the details of the survey. I really badly need a help regarding with this. Thanks . . .
change $.ajax function like below
$.ajax({
url: '<?php echo base_url(); ?>index.php/admin/survey/act_surveyby_id',
type: "POST",
data: {
idx : idx;
},
and controller like below
public function act_surveyby_id(){
$id=$_POST['idx'];
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id))
{
echo "success";
}else{
echo "invalid";
}
}

load a php query file in an html index page using ajax or jquery

index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "query.php",
data: data,
beforeSend: function(html) { // this happens before actual
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html)
{ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
$(document).ready(function{
$.ajax({
url: "query.php"
}).done(function(data) {
$('body').html(data);
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "query.php",
dataType: "text",
data: dataString,
success: function (response)
{
alert(response); //alert responce from query.php
},
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr);
}
});
});
</script>
</head>
<body >
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="query.php" >
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults"></div>
<ul id="results" class="update">
</ul>
</div>
</div>
</body>
</html>
query.php
<?php
$user_name = "root";
$password = "";
$database = "my_db2";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL = "SELECT * FROM user WHERE Hometown = 'Quahog'";
//searching for what was entered into the search box
if (isset($_POST['search']))
{
$search_term = mysql_real_escape_string($_POST['search']);
//concatenating the $SQL variable above
$SQL .= "AND id = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND FirstName = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND LastName = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND Age = '{$search_term}'";
$SQL .= "OR Hometown = 'Quahog' AND Job = '{$search_term}'";
}
$result = mysql_query($SQL) or die(mysql_error());
?>
<html>
</head>
<body>
<h1> Persons</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong>ID</strong></td>
<td><strong>First Name</strong></td>
<td><strong>Last Name</strong></td>
<td><strong>Age</strong></td>
<td><strong>Hometown</strong></td>
<td><strong>Job</strong></td>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['FirstName']; ?></td>
<td><?php echo $row['LastName']; ?></td>
<td><?php echo $row['Age']; ?></td>
<td><?php echo $row['Hometown']; ?></td>
<td><?php echo $row['Job']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
I am new to javascript, jquery and ajax and I would like some help on modifying the above code so that when the page loads, I can view the results of a php/mysql query named 'query.php' into the index file of my html page.
Any help will be greatly appreciated.
$(document).ready(function() {
jQuery.ajax({
type: "POST", // this is post request u can also do get request
url: "query.php",
dataType: "text",
success: function (response) // this is the response from url: "query.php",
{
alert(response); //alert responce from query.php and here you can do
// whatever u like with response.
},
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr); // if any error function.
}
});
});
Use AJAX in yout index.html like this:
$(document).ready(function{
$.ajax({
url: "query.php"
}).done(function(data) {
$('body').html(data);
});
});
More info on AJAX.
Make sure that you have included jQuery in your code.

Ajax call with javascript not working

I want to try to get some value from page cart.php from and ajax call, but its not working.
Ajax code is below:
function temp_sell(id) {
//var p_id=document.getElementById('temp').value;
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: "value=" + p_id,
success: function (message) {
alert(message);
$("#your_cart").html(message);
}
});
}
temp_sell.php is below where I want to show some products details
<?php
include("connection.php");
echo $p_id = $_POST['value'];
$qty=1;
$query="SELECT * FROM product WHERE id='$p_id'";
$result=mysql_query($query);
while($data=mysql_fetch_array($result))
{
?>
<form>
<table>
<tr>
<img src="<?php echo "img/".$data['image'];?>"/>
<strong><?php echo $data['pro_name'];?></strong>
<strong><?php echo $data['price'];?></strong>
<input type="text" value="<?php echo $qty;?>"/>
</tr>
</table>
</form>
<?php
}
?>
p_id is undefined, you have commented the p_id value or change temp_sell(p_id).
function temp_sell(p_id)
instead of
function temp_sell(id)
Reference comments : Ajax call with javascript not working
Do this :
function temp_sell(id){
var p_id=document.getElementById('temp').value; // <--- uncomment this line
alert(p_id);
$.ajax({
type: "POST",
url: "temp_sell.php",
data: {value:p_id}, // <--- change this
success: function(message){
alert(message);
$("#your_cart").html(message);
}
});
}

Categories