Click is not working in jQuery Ajax - javascript

I have an image with the Coupon code in Front End/Homepage of my website but when I try to click that nothing happens and click is not working.
The Html is below
<a class="coupon_click text-no-decoration" href="javascript:void(0);" id="coupon_id_<?php echo $couponBanner->getId(); ?>">
jQuery code is below
jQuery(document).ready(function () {
jQuery('.coupon_click').click(function () {
console.log('here');
jQuery.ajax({
type: 'POST',
url: '<?php echo url_for('#blog_couponClicked') ?>',
data: {videoId: <?php echo $video_id ?>, couponId: <?php echo $couponBanner->getId(); ?>},
success: function (res) {
if (res) {
window.location.href = res;
}
}
});
});
});

Hi my advise don't mess the JQuery Code and PHP and make it clean as much as possible,
<a class="coupon_click text-no-decoration" href="javascript:void(0);" c-id="coupon_id_<?php echo $couponBanner->getId(); ?>" v-id="<?php echo $video_id ?>">Click</>
jQuery(document).ready(function() {
jQuery('.coupon_click').on('click', function () {
console.log('here');
var cid= jQuery(this).attr('c-id');
var vid= jQuery(this).attr('v-id');
dataCall(vid,cid);
})
function dataCall(vId, cId){
jQuery.ajax({
type: 'POST',
url: 'your_url',
data: {videoId: vId,couponId:cId},
success: function (res) {
//do whatever you want to do
},error:function(err){
console.log(err);
}
})
}
})

hope it's what u want
<a id="coupon" class="" href="javascript:void(0);" id="coupon_id">coupon</a>
$("document").ready(function()
{
$("#coupon").click(function ()
{
sendS();
});
});
function sendS()
{
var couponID="abc123";//anythg u like
var userID="hahaha#mail.com";
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{cID:couponID,uID:userID},
success: function(data)
{
alert(data)
},
error: function ()
{
alert("Error!");
}
});
}

Related

Update javascript variables after ajax call

I'm attempting to dynamically update a notice after the cart is updated via ajax. I can't seem to figure out how to re-update all variables so the calculation loop could run again. I tried wrapping the if statement into a function and calling that again inside of updated_wc_div but that didn't work.
Any suggestions?
( function($) {
var membership_price = membership.price;
//grab cart total from html
var total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
compared_price = parseInt(membership_price) - total;
//everything runs fine on load.
if ( total < membership_price ) {
message = 'For <strong>$'+ compared_price +'</strong> more, gain access to unlimited downloads. Become a member!';
notice = '<div class="woocommerce-info">' + message + '</div>';
$('.woocommerce-notices-wrapper').html(notice);
}
//running this to know when ajax is called
$(document.body).on('updated_wc_div',function( event ){
$('.woocommerce-notices-wrapper').empty();
total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
//I believe problem is here, it doesn't update variable so it could loop again.
});
} )(jQuery);
this is how I dynamically update an object after ajax call is being called:
function getCart(user_id) {
$.ajax({
type: "POST",
url: "get_total_cart.php",
data: {
'user_id': <?php echo $user_id; ?>
},
beforeSend: function() {},
success: function(response) {
var user = JSON.parse(response);
var total_cart = parseInt(user.total_cart);
$("#total_cart").html(total_cart);
}
});
}
function addCart(product_id, user_id) {
$.ajax({
type: "POST",
url: "add_cart.php",
data: {
'product_id': product_id,
'user_id': user_id
},
beforeSend: function() {},
success: function(response) {
getCart(user_id);
}
});
}
$(document).ready(function() {
$(".se-pre-con").fadeOut("slow");
getCart(<?php echo $user_id; ?>);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_cart">Total Cart</div>
<input type="button" name="add_cart" id="add_cart" value="Add to Cart" onclick="addCart('<?php echo $product[id]; ?>', '<?php echo $user_id; ?>')" class="btn btn-info">
I hope this helps.
Cheers.
Simply you have to put your function inside the ajax function or make the ajax function "async:false"
$.ajax({
type: "POST",
url: "",
async:false, // <======== remove asynchronous property
data: {},
success: function(result) {
}
});
////////////////////////////////////////////////
$.ajax({
type: "POST",
url: "",
data: {},
success: function(result) {
// Or put your function here
}
});

CodeIgniter 3: Submit to Controller in Ajax

I'm trying to create a notification feature and I wanted the ajax to be able to run a query via the controller on button click
THIS IS MY SCRIPT
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>'
});
});
THE CONTROLLER
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
return;
}
AND THE MODEL
function read_notifs($id)
{
$read = array(
'read' => '1'
);
$this->db->where('recipient', $id);
$this->db->update('tbl_notifications', $read);
return;
}
I tried this and the data in the database doesn't update.
IN MY HTML IT IS JUST A SIMPLE BUTTON
Script
$('#noti_Button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});
Controller
public function read_notif(){
$this->profile_model->read_notifs($data['id']);
echo $this->db->last_query();
}
It is the sample calling the ajax in ruby on rails . In this code we are calling the controller for getting the values.
$('#Button').on('change', function(event) {
var selected_resource_id = $(this).val();
$.ajax({
type: 'GET',
url: "<%= Home_index_path %>",
data: { id: selected_resource_id },
success: function (data) {
alert("Ajax success");
}
});
});
use error: to check if there's any error in submitting your form.
$('#button').click(function (e) {
e.preventDefault();
$.ajax({
url: '<?php echo site_url("profile/read_notif")?>',
success:function(data)
{
alert(data);
}
});
});

jQuery Ajax if variable on submit is ok hide button

I am trying to hide the submit button if the email is the same with the one in the database from action.php. How could I implement this in my following code:
<form onsubmit="return submitdata();">
<input type="text" id="mail">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('mail').value;
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
console.log(data);
$('#msg').html(data);
}
});
return false;
}
</script>
action.php:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "Response: ".$email;
$hide = 1;
}else{
echo 'hmmmm';
}
?>
When the email coincide I get the correct message, but how could I call back $hide to determine to hide my submit button?
Instead of returning a message, return an indication.
(In the JS script write the message accordingly)
A detailed json string would be a good idea but for simplification see the following.
PHP:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "already_exists";
}else{
echo 'not_exists';
}
?>
JS:
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
if(data == 'already_exists'){
$('#buttonId').hide();
} else if(data == 'not_exists'){
$('#msg').html('Response: ' +name);
}
}
});

Need to be able to get the return string from javascript method in yii2

I am working on Yii2 and having a problem with returning the content of the javascript method to be sent when using the Html::a -hyperlink
The javascipt is in order to obtain the selected value of the checkboxes and it is outputting correctly.
<script>
function getNewPermissions() {
var permissions = '';
var rows = $(document).find('.permission');
$.each(rows, function (key, value) {
if($(value).find('input').prop('checked') == true)
permissions += value.id+'$&/';
})
permissions = permissions.substring(0, permissions.lastIndexOf("$&/"));
return permissions;
}
</script>
echo Html::a(Yii::t('app', 'Edit'), ['permissions/edit' ,'id'=> $name], [
'class' => 'btn btn-primary',
'onclick' =>'js:getNewPermissions()',
'data-method' => 'post',
'data' => [
'params' => ['newPerms'=>'js:getNewPermissions()','_csrf' => Yii::$app->request->csrfToken],
],
])
In the yii1 the value was read correctly from the params.
Just cant find any source to help get js in the params directly and the onclick does work.
in my project use another way
<a style="float:left;" class="btn btn-success" onclick="myFunction(this)"
type="<?php echo $value->id; ?>">
</a>
and use js function in end of layout
<script>
function updateSession(e)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
var pid = e.getAttribute('type');
var key = e.getAttribute('title');
var pqty = $("#id_" + key).val()
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/updatecard') ?>',
type: 'Post',
data: {
productid: pid,
key: key,
pqty: pqty,
_csrf: csrfToken
},
success: function (data) {
alert(data);
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcard') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#collapseCart").empty();
$("#collapseCart").append(data);
}
});
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcardpage') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#get_card2").empty();
$("#get_card2").append(data);
}
});
}
});
}
</script>

how to redirect the request to specified php page by ajax call?

how to redirect the request to specified php page by ajax call, below is my code structure
index.html
<html>
<script>
function shift(str)
{
$.ajax({
url: 'destination.php',
type:'POST',
data: {q:str}
}).done(function( data) {
$("#result").html(data);
});
return false;
}
</script>
<body>
<input type='button' value='test' onclick="shift('test');">
<div id='result'></div>
</html>
destination.php
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
header('something.php');
}
else
{
echo "test";
}
?>
this is my code structure if posted string is same as then header funtion should be work else echo something, but header funstion is not working via ajax
You should specify header parameter to Location. Use the code below
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
header('Location:something.php');
}
else
{
echo "test";
}
?>
Hope this helps you
Go With This
You can check the string in jquery like below..
First you must echo the variable in php page.
then,
$.ajax({
url: 'destination.php',
type:'POST',
data: {q:str}
}).done(function( data) {
if(data=="something")
{
window.location.assign("http://www.your_url.com"); //
}
});
return false;
}
You should always retrieve the response in json format and based on that decide where to redirect. use below code for your requirement.
function shift(str) {
$.ajax({
url: 'destination.php',
type: 'POST',
data: {
q: str
}
}).done(function (resp) {
var obj = jQuery.parseJSON(resp);
if (obj.status) {
$("#result").html(obj.data);
} else {
window.location..href = "YOURFILE.php";
}
});
return false;
}
Destination.php
<?php
$string=$_REQUEST['q'];
$array = array();
if($string=="something")
{
$array['status'] = false;
$array['data'] = $string;
}else {
$array['status'] = true;
$array['data'] = $string;
}
echo json_encode($array);
exit;
?>
function shift(str) {
$.ajax({
url: 'destination.php',
type: 'POST',
data: {
q: str
}
}).done(function (data) {
if (data=="something") {
window.location.href = 'something.php';
}
else {
$("#result").html(data);
}
});
return false;
}
in Destination.php
<?php
$string=$_REQUEST['q'];
if($string=="something")
{
echo "something";
}
else
{
echo "test";
}
?>

Categories