I tried to post values while checked the checkbox using ajax, but it fail, the code seems right to me.. on the url it's appear like this, that it shouldn't..
http://localhost/logsys/admin/roleaccess/%3C?%20$role[%27id%27];%20?%3E
I'm using codeigniter v 3.1.10, running on xampp v 7.3.0
<script>
$('.form-check-input').on('click', function() {
const menuId = $(this).data('menu');
const roleId = $(this).data('role');
$.ajax({
url: "<?= base_url('admin/changeaccess'); ?>",
type: 'post',
data: {
menuId: menuId,
roleId: roleId
},
success: function() {
document.location.href = "<?= base_url('admin/roleaccess/'); ?>" + roleId;
}
});
});
</script>
It should pass the value that allows user get access for some menu
<script>
$('.form-check-input').on('click', function() {
const menuId = $(this).data('menu');
const roleId = $(this).data('role'); // roleId = <? $role[‘id’] ?> so php did not echo role id here
$.ajax({
url: "<?= base_url('admin/changeaccess'); ?>",
type: 'post',
data: {
menuId: menuId,
roleId: roleId
},
success: function() {
document.location.href = "<?= base_url('admin/roleaccess/'); ?>" + roleId;
}
});
});
</script>
For solution change your form-check-input element
<... class=“form-check-input” data-role=“<?php echo $role[‘id’]; ?>” data-menu=“echo menu variable” ...>
If this doesn’t work to share your html of form-check-input button
Related
I want to redirect the browser to the login page if SESSION is not set and a customer clicks on Add to cart button.
I Have written this code window.location.replace("http://app.test/pages/login.php"); for redirecting to the login page if the customer_id is empty. but it doesn't redirect to this page.
<script>
$(document).ready(function() {
CountProducts();
$('.add_cart').on('click', function(e) {
e.preventDefault();
var $container = $(this).closest('.col-sm-12');
var name = $container.find('.name').val();
var hiddenID = $container.find('.hiddenID').val();
var price = $container.find('.price').val();
var category = $container.find('.category').val();
var customer_id = <?php echo $_SESSION['customer_id']?>;
if(customer_id === '')
{
window.location.replace("http://app.test/pages/login.php");
}
else{
$.ajax({
url: "Ajax/add_to_cart.php",
type: "post",
data: {
name: name,
hiddenID: hiddenID,
price: price,
category: category
},
success: function(output) {
CountProducts();
}
});
}
});
});
</script>
Try below code:
if( customer_id > 0 ) {
$.ajax({
url: "Ajax/add_to_cart.php",
type: "POST",
data: {
name: name,
hiddenID: hiddenID,
price: price,
category: category
},
success: function(output) {
CountProducts();
}
});
}
else {
window.location.href = "http://app.test/pages/login.php";
}
Ok, Thanks for Helping. I forgot to put this code var customer_id = <?php echo $_SESSION['customer_id']?>; in quotes Now i write it like this var customer_id = '<?php echo $_SESSION['customer_id']?>'; and it works.
I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'
I am building a news page for my website but I'm stuck displaying the right comments with ajax...
commentsLoad.php
<?php
include('config.php');
$newsid = $_GET['newsid'];
$comments=array();
$commentsQuery = "SELECT * FROM comments
where fk_news like ".$newsid;
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[]=array('id' => $row['id'], 'name' => $row['cnick'], 'text' => $row['ctext'], 'date' => $row['cdate']);
}
}
//header('Content-type: application/json');
echo json_encode($comments);
exit;
?>
I dont know how to pass the right 'NEWSID'.
Website picture: http://prntscr.com/8nwy8k
How I want to pass that ID to the SQL Query
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:'1'},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
So right now if I change the line data:{newsid:'1 or 2 or 3...'} I get the comments I want, but I dont know how to get that ID into a variable.
You can use onClick event for this.
Explanation:
Comment link will look as follows
Comments
Then you can have a fucntion in your JQuery code to pass it to PHP file.
function getComments(article_id)
{
var artid = article_id;
$.ajax({
type: 'POST',
url: commentsUrl,
dataType: "json",
data:{newsid: artid},
success: function(comments){
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
Try set onclick function in the comment link.
<a href="javascript:void(0)" onclick='myfunction <?php echo newsid ?>'Comment</a>
Get the newsid form the link.
<script>
function myfunction(newsid){
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:newsid},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
</script>
Get the newid from commenntsUrl page.
I'm running a database with itemID's and a shelfnumber for every itemID..
As the user enters an itemID I want it to run through my database to get the shelfnumber using Ajax/PHP. Then post the shelfnumber back so the user can see where to find the item. (The items are in a room and are marked with unique ID's and shared shelfnumbers.) I need to use the onChange method (or anything similar) beacuse I want it to work like a tip/search engine. In other words automatic..
I'm totally new to ajax and I can't seem to get this to work at all.. No result is given and i'm at a roadblock right now.. Any form of help will be very appreciated
HTML
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
}
});
});
</script>
</head>
<body>
<a>Enter Item ID 1:</a>
<input id="target" type="text" name="itemID" required />
<div id="hyllplacering">ENTER Shelfnumber here: </div>
</body>
</html>
PHP
<?php
$con = mysql_connect("localhost", "root", "") OR die(' Could not connect');
$db = mysql_select_db('book1', $con);
$itemID = filter_input(INPUT_POST, 'itemID', FILTER_VALIDATE_INT);
$query = "SELECT Hyllplacering from booking WHERE itemID = $itemID";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo json_encode(array('itemID' => $itemID, 'Hyllplacering' => $row['Hyllplacering']));
?>
JavaScript is executed as soon as it is encountered. You bind the Event to an Element before it is available.
You need to wrap the script in a document.ready body.
As the other answers mentioned you want to use the success callback instead of done.
<script>
$(document).ready(function(){
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
})
.success(function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
});
});
});
</script>
You may add a sentence in AJAX function
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
success:function(data){
console.info(data);
}
})
to monitor what your PHP responsed, it's more easy to check what's wrong.
I think you incorrect to use the done method of the Ajax object. I am pretty sure you wont have your response available in that scope. Try to do it like..
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
},
error:function(response){
alert('error '+response);
};
})
});
I am trying to pass the form field values to a php function located into a file. The problem is that I can't understand how to pass that serialized form data to the function from this ajax to a function in php.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
$('#insert_news').serialize(); // how do I add this data here?
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
This ajax passed the values to the file ajax.php right beyond. And from ajax.php is called the function located in functions.php.
ajax.php
if (isset($_POST['action']) && $_POST['action'] == 'insert_news') {
$cp->insert_into_table('newss', array(
'NewsTitle' => $_POST['title'],
'NewsDescrption' => $_POST['description'],
'Date' => date('Y-m-d H:i:s'),
'status' => '1'
)
);
}
function.php
public function insert_into_table($table_name, array $data){
foreach($data as $col=>$value) {
$cols[] = $col;
$values[] = '\''.$value.'\'';
}
$cols = implode(', ', $cols);
$values = implode(', ', $values);
$this->db->query("INSERT INTO $table_name ($cols) VALUES ($values)");
echo "INSERT INTO $table_name ($cols) VALUES ($values)";
}
The issue is serialize() produces a URL encoded key value paired string, so you can't mix that with your data object.
You can use serializeArray() to get an array of objects, representing the form elements, then iterate over them and add them to a data object:
var data = { action: 'insert_news' };
$.each($('#insert_news').serializeArray(), function(){
data[this.name] = this.value;
});
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: data,
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
Side note: your PHP code is vulnerable to SQL Injection. Consider using a Prepared Statement instead of concatenating user input into the SQL.
You can pass serialized data via ajax to a function the way you are doing but your code needs slight modification.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
serializedData: form // use variable to assign data here
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
I think you can use alternate like this
First : add hidden input for action on your form
<input type="hidden" name="action" value="insert_news"/>
Then your ajax post like this
$('#insert_news').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: $(this).serialize(), // $(this) is from <form id="insert_news">
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
And then use print_r on your ajax.php
print_r($_POST);
$('#insert_news').submit(function(event) {
var name = $("#t1").val();
var pass = $("#t2").val(); //add more var as u need
var key = 0;
var formName = new FormData();
formName.append(key++,name)
formName.append(key++,pass) //append the the var to formdata
$.ajax({
url : 'includes/ajax.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formName,
type : 'post',
success : function(data){
$('#message').html(data).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
this works fine for me :-)