I'm facing with this problem : I have made a button report on every comment in a website to let people to report comment. I want if someone click on the button to be redirected to the popup window to let the people to login or register. I want after login/register is done this request(count) is send to database.
My problem is how can I perform this inside jQuery code :
if(isset($_SESSION['session_user'])) { /*do something*/ }.
Here is the code of what I already do :
return this.each(function (i) {
var count = 0;
$(this).append("<button class='" + parametres.button + " report" + i + "''><span class='glyphicon glyphicon-alert'> </span>" + parametres.textBtn + "</button>").on('click', function () {
// if ("<%php !$_SESSION['user_session'] %>") {
// Popup window
$('#myModal').modal('show');
// pane register
$('.btnReg').on('click', function () {
$.ajax({
url: 'includes/register.php',
data: {name: $('#nameReg').val(), email: $('#emailReg').val(), password: $('#passwordReg').val()},
type: 'POST',
beforeSend: function () {
//$('#error').fadeOut();
$("#error").html('<div class="alert alert-info"> <span class="glyphicon glyphicon-transfer">Envoi en Cours ...</span></div>');
},
success: function (data) {
if (data == 'exist') {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>Ce mail n\'est pas disponible !</div>');
} else if (data == 'success') {
$("#error").html('<div class="alert alert-success"> <span class="glyphicon glyphicon-info-sign"></span>Inscripton effectuée !</div>');
} else {
$("#error").fadeIn(1000, function () {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span>' + data + ' !</div>');
});
}
}
});
});
// pane login
$('.btnLog').on('click', function (elem, i) {
//event.preventDefault();
$.ajax({
url: 'includes/login.php',
data: {email: $('#emailLog').val(), password: $('#passwordLog').val()},
type: 'POST',
success: function (data) {
if (data == 'success') {
$("#error").html('<div class="alert alert-info"> <span class="glyphicon glyphicon-transfer">Connexion en Cours...</span></div>');
setTimeout(' window.location.href = "index.php"; ', 4000);
} else { //alert(data);
$("#error").fadeIn(1000, function () {
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span>' + data + ' !</div>');
});
}
}
});
});
//}
//This is the thing to be done after login, where to put it ?
count = count + 1;
if (count >= parametres.juge) {
var content = $(this).text();
var click = count;
var tag = "<button class='" + parametres.button + " report" + i + "''>" + parametres.textBtn + "</button>";
$.ajax({
url: 'includes/controller.php',
data: {content: content,
click: click,
tag: tag},
type: 'POST',
success: function (data) {
if (!data.error) {
//alert(data);
alert('Success!');
}
}
});
$(this).animate({'opacity': 0}, 1000, function () {
$(this).text(parametres.textReplace).css('color', parametres.colorTex);
}).animate({'opacity': 1}, 1000);
}
});
});
You can use php to determine whether or not the user is logged in, and if they are print their id into a hidden input variable.
<?php isset($_SESSION['session_user']): ?>
<input type="hidden" id="session_user_id" value="<?php echo $_SESSION['session_user_id']; ?>">
<?php endif; ?>
Then in js when you need the id, you can use jquery to find it:
var session_user_id = $('#session_user_id').val();
Have you tried like this
if( <?php isset($_SESSION['session_user']) ?>) { do something }.
Related
I'm have an html table with modal column (see image below for your reference)
Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)
I wanted to access and used it in my Add function using ajax but I'm having an error of "customer_id is not defined" when I tried to use it. Is there a way to fix it or do it properly.
This is my script
<script>
$(document).ready(function () {
// START OPEN CART MODAL FUNCTION
$(document).on('click', '.viewCart', function (e) {
e.preventDefault();
var customer_id = 0;
var customer_id = $(this).val();
console.log(customer_id);
$.ajax({
type: "GET",
url: "/get-cart/"+customer_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr>\
<td>' + item.p_name + '</td>\
<td>' + item.c_qty + '</td>\
<td class="total">' + item.p_amt + '</td>\
<td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>\
\</tr>');
});
}
}
});
});
// END OPEN CART MODAL FUNCTION
// START ADD DATA FUNCTION
$(document).on('click', '.addToCart', function (e) {
e.preventDefault();
var data = {
'store': $('.sel_store').val(),
'product': $('.sel_product').val(),
'quantity': $('.sel_qty').val(),
// HOW TO INPUT Customer ID here, I tried this but im having an error of
// customer_id is not defined
'customer_id': customer_id,
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/cart-list",
data: data,
dataType: "json",
success: function (response) {
}
});
});
// END ADD DATA FUNCTION
});
</script>
In case that chosen attributes are the same, after clicking "Save button" - button disappears.
(it disappears from code, got deleted)
[Image before clicking][1]
[Image after clicking][2]
Most confusing thing is that, add button was coded the same but it works well...
I've got no clue what might be the case here.
Button:
<input type="button" height="20" class="btn btn-warning" onclick="return saveEdit()" value="Save" />
function saveEdit() {
var elem = $('#Domain_Edit');
$.ajax({
url: "/Domain/DomainEdit",
type: "post",
data: elem.serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
alert(window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage);
}
else
{
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Code of button on page:
<input type="button" height="20" class="btn btn-warning" onclick="return btnSave('89515a0b-a671-4eff-a0eb-61c1d268f696')" value="Save">
function btnSave(id) {
var elem = $("." + id).closest('#DomainTrust_Edit');
$.ajax({
url: "/Domain/DomainTrustEdit",
type: "post",
data: $("." + id).closest('#DomainTrust_Edit').serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
// The controller action returned a JSON object with the redirectTo property
window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage;
} else {
// The controller action returned a partial view with the form and the errors so update of the containing FORM with it is needed.
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Is your button located inside the #Domain_Edit element?
Since .html(result) replaces all html inside #Domain_Edit so if your button is inside that element, that would explain why it got removed.
Upon ajax successful return, the return data contains status. if status is false(not ajax fail), return data contains array of element names and associated error message. The goal is to replicate .validate() error functionality by appending msg after element and highlight.
HTML form:
<form class="form-horizontal" id="chngPwdForm" action="changepwd.php" method="post">
.
. various HTML....
.
<div class="form-group">
<div class="alert alert-div font-weight-bold" id="errorTxt" role="alert" style="display:none;"> </div>
<label for="crntPwd">Existing Password:</label>
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key fa-fw"></i></span>
<input type="password" class="form-control" id="crntPwd" name="crntPwd" required>
</div>
</div>
.
. more HTML follows
.
JQUERY:
.
.yada, yada, yada
.
$("#chngPwdForm").submit(function(event){
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $("#chngPwdForm").attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var element;
var errorObj = new Error("");
$.each(data.Msg, function(elemName, errMsg) {
element = $("#chngPwdForm").filter("#" + elemName);
errorObj.message = errMsg;
$(element).closest(".form-group").addClass("has-error");
errorObj.insertAfter(element);
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
.fail (function(response){
var Msg = "chngPwd call failed. errorThrown: " + response;
var obj = JSON.stringify(response);
alert("obj is: " + obj);
$('#chngPwdForm div[id="errorTxt"]').text(Msg);
})
}
else {
$('#chngPwdForm div[id="errorTxt"]').text('Please Correct errors').show();
}
return false;
The JSON response from changepwd.php:
{\"status\":false,\"Msg\":{\"crntPwd\":\"Current Password may only contain a-z, A-Z, 0-9, ! or #\"}
JS error
"TypeError: errorObj.insertAfter is not a function" is thrown for
"errorObj.insertAfter(element);"
The implemented solution:
JQuery:
// New Code has leading and trailing *
$("#chngPwdForm").submit(function(event){
*$(".chngPwderr").removeClass("error").text('');* //used to remove old messages
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $(this).attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var focusSet = false;
$.each(data.Msg, function(elemName, errMsg) {
*$("#" + elemName).attr("type", "text");
if (!$("#" + elemName).parent().hasClass("error")) {
$("#" + elemName).parent().append('<div class="chngPwderr error">' + errMsg + '</div>');
}
if (!focusSet) {
$("#" + elemName).focus();
focusSet = true;
}*
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
i have the 2 scripts below that pretty much do the same thing however are for 2 different sets of forms but get posted to the same page via ajax my question is there a way to minimize the amount of code required to do the job
like for example $(document).on('submit', 'form.frm_details','form.wa_cu_del', function(event)
<script>
$(function() {
$(document).on('submit', 'form.frm_details', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if(data.status == '1') {
$('#info').html('<div class=\"alert alert-success alert-styled-left alert-arrow-left alert-bordered\"> ' + data.message + '<button type=\"button\" class=\"close\" data-dismiss=\"alert\" >×</button></div>');
$('.my-modals').modal('hide');
webapp_get_customers();
document.getElementById('frm_details0').reset();
}
if(data.status == '2') {
$('#info').html('<div class=\"alert alert-danger alert-styled-left alert-arrow-left alert-bordered\">' + data.message + '<button type=\"button\" class=\"close\" data-dismiss=\"alert\" >×</button></div>');
$('.my-modals').modal('hide');
}
}
});
});
});
</script>
<script>
$(function() {
$(document).on('submit', 'form.wa_cu_del', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if(data.status == '2') {
$('.my-modals').modal('hide');
$('#info').html('<div class=\"alert alert-danger alert-styled-left alert-arrow-left alert-bordered\"> ' + data.message + '<button type=\"button\" class=\"close\" data-dismiss=\"alert\" >×</button></div>');
webapp_get_customers();
}
}
});
});
});
</script>
There is a change in your code, instead of
$(document).on('submit', 'form.frm_details','form.wa_cu_del', function(event)
you had to write
$(document).on('submit', 'form.frm_details, form.wa_cu_del', function(event)
Fiddle
I am trying to learn AJAX from a tutorial.
I am able to grab the data I want and populate it in the DOM pretty easily.
What I'm struggling with is using 'POST' to edit it.
I created a simple page that lists 'friends' and 'ages' that pulls that data from here
http://rest.learncode.academy/api/learncode/friends
The names and ages populate correctly, but the code I'm writing to 'POST' to it is not.
Here is my javascript
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/learncode/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
</script>
HTML
<div class="large-12 columns" id="ajaxContainer">
<h1>
AJAX Container
</h1>
<h3>
Friends
</h3>
<ul id="friends">
</ul>
<h3>Add a friend</h3>
<p>
Name:
<input type="text" id="name" />
</p>
<p>
Age:
<input type="text" id="age" />
</p>
<button id="add-order"> submit</button>
</div>
I am guessing as to what you actually want, but it seems that you want the page to populate with whatever friends are currently in the database on first load, and then when you click add-order button, it adds new friends and updates your list. The first thing is that you are trying to POST to the learncode name, which you can't do. Change where it says "yourname" in the URLs below to something else. Here is what you should do:
<script>
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
$.ajax({
type: 'POST',
data: {"id":3, "age": $age.val(), "name":$name.val()},
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function () {
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/yourname/friends',
success: function (data) {
$friends.html("");
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +'
</li>');
})
},
error: function () {
alert("error loading data");
}
});
},
error: function () {
alert("error loading data");
}
});
});
});
</script>
See the part that says
type : "GET"
-?-
change it to
type : "POST"
Then, the url parameter is what you are POSTing to-
And you are not actually sending any data -!
So, try this:
$(function () {
var $friends = $('#friends');
var $name = $('#name');
var $age = $('#age');
$.ajax({
type: 'POST',
url: 'http://yourWebsite.com/someScriptToHandleThePost.php',
data: [{"id":1,"name":"Will","age":33},{"id":2,"name":"Laura","age":27}],
success: function (data) {
console.log("I have friends!", data);
$.each(data, function(i, name){
$friends.append('<li>name: '+ name.name + '<br />' + ' age:' + name.age +' </li>');
})
},
error: function () {
alert("error loading data");
}
});
$('#add-order').on('click', function () {
});
});
Then, you're going to need a PHP script to handle the POSTed data and return a response, which gets passed in the data param in success:function(data){}
start out with something simple, like this:
<?php
print_r($_POST);
?>
and change your success function to:
success: function(data) {
$("body").append("<pre>"+data+"</pre>");
}
and that should get you on the right track....