I just created an x-editable form :
<a href='#' class='username'
data-pk='<?php echo $key['idca']; ?>'
data-type="text"
data-placement="right"> <?php echo $key['categoryname']; ?> </a>
Then I created Javascript function to handle x-editable form :
$.fn.editable.defaults.success = function() { $(this).show() };
$.fn.editable.defaults.mode = 'inline';
$('.username').editable({
url:'edit.php',
pk:'1',
type:'text',
send:'always',
ajaxOptions:{
dataType:'json'
},
success: function(response, newValue) {
window.alert('oke');
},
error: function(response, newValue) {
window.alert('failed');
}
});
and in PHP I just create as follow :
<?php
$pk = $_POST['pk'];
$val = $_POST['value'];
$name = $_POST['name'];
print_r($_POST);
?>
But why I received message "undefined index pk, value, name" on window alert, which means I failed posting pk, value, name from x-editable..
Need helps, thank you very much
Given the following HTML
<a href="#" class="username"
data-pk="<?php echo $key['idca']; ?>"
data-type="text"
data-placement="right"
>
<?php echo $key['categoryname']; ?>
</a>
You can use this jQuery:
$.fn.editable.defaults.success = function() { $(this).show() };
$('#username').editable({
type: 'text', // optionnal if you've set up the data-type attribute
pk: $(this).data('pk'), // optionnal if you've set up the data-pk attribute
url: 'edit.php', // mandatory
title: 'Enter username'
});
This should work as per the documentation. There is no need for you to do the $.ajax({}); by yourself.
A little late but on php side when you response you should use json_encode because x-editable is expecting you to return with json string.
$pk = $_POST['pk'];
$val = $_POST['value'];
$name = $_POST['name'];
echo json_encode($_POST);
die();
Related
working around with this code, but can not find what is wrong.
the following code is as follows:
$_POST from php filling attributes
<button class="final-buy-now-btn" type="submit"
book="<?php echo $_POST['book'];?>"
productId="<?php echo $thisProductId?>"
value="<?php echo $thisProductId ?>"
<?php if($book === 'christmas'){ echo "country=\"".$thiscountry."\" ";
echo "city=\"".$thiscity."\">";} ?>
<?php if($book === 'birthday'){ echo "bday=\"".$bday."\" ";
echo "month=\"".$month."\">";} ?>
<a>Buy Now</a>
</button>
after that i am calling final-buy-now-btn which i expect to be making the error, but i couldnt find it:
$('.final-buy-now-btn').click(function(event){
var book = $(this).attr("book");
var productId = $(this).attr("productId");
if( book === "christmas" ){
var country = $(this).attr("country");
var city = $(this).attr("city");
$.ajax({
type: 'POST',
url: '../../wp-admin/admin-ajax.php',
data: { 'action' : 'add_item_meta_data_to_cart_item',
'book' : book, 'productId' : productId,
'country' : country,'city' : city},
success: function (res) {
if (res) {
window.location = 'index.php/cart/';
}
}
})
}
if(book === "birthday"){
var month = $(this).attr("month");
var bday = $(this).attr("bday");
$.ajax({
type: 'POST',
url: '../../wp-admin/admin-ajax.php',
data: {
'action' : 'add_item_meta_data_to_cart_item',
'book' : book,'productId' : productId,
'month' : month,'bday' : bday},
success: function (res) {
if (res) {
window.location = 'index.php/cart/';
}
}
})
}
});
then finally from the action that is called, which is my php function,
for birthday the values are getting returned but for christmas nothing is getting returned.
function add_item_meta_data_to_cart_item( $cart_item_data, $product_id, $variation_id ) {
$item_meta_data = filter_input( INPUT_POST, 'item_meta_data' );
$item_meta_data = json_decode($item_meta_data);
echo "<pre>";
print_r($item_meta_data);
echo "</pre>";
The short answer is that you have typo:
if( book === "chritmas" ){
You forgot letter s in JavaScript code
Other things
You should:
Using input type hidden instead of attributes or replace attributes to data-city, data-book
Remove attribute <a> in button
looking at your code, it doesn't appear that you are closing the button tag. try this snippet with the extra > after the month property.
<button class="final-buy-now-btn" type="submit"
book="<?php echo $_POST['book'];?>"
productId="<?php echo $thisProductId?>"
value="<?php echo $thisProductId ?>"
<?php if($book === 'christmas'){ echo "country=\"".$thiscountry."\" ";
echo "city=\"".$thiscity."\">";} ?>
<?php if($book === 'birthday'){ echo "bday=\"".$bday."\" ";
echo "month=\"".$month."\">";} ?>>
<a>Buy Now</a>
</button>
if its still not working, run the page through https://validator.w3.org/ to look at the html output and see if they are any other syntax errors.
as rafael mentioned: data-field is the best practice for naming properties in tags.
I´m trying to call a function into a href, my function is on functions.php
and my href is on views/something.php
so, this is my function:
function discount($connection, $us){
$discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
$discount->execute();
return $discount;
}
and my link button is on an <li> (not in a form):
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
(Do not pay attention to the foreach)
You'll need to change this to use an ajax call or form post to call the PHP function.
Here's a really basic example which should point you in the right direction
discount.php
<?php
// Load $connection from somewhere
// Get user, it's better to get this from a cookie or session rather than GET
$user = $_GET['user']
$discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
$discount->bindParam(':user', $user);
$result = $discount->execute();
// Throw error if something went wrong with the update, this will cause $.ajax to use the error function
if (!$result) {
http_response_code(500);
}
html, assuming $notu[0] contains the user id
<?php foreach ($total_notu as $notu) : ?>
<li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
js, requires jquery
function callDiscount(user_id)
{
// Perform ajax call to discount.php
$.ajax({
url: '/discount.php?user=' + user_id,
error: function() {
alert('An error occurred');
},
success: function(data) {
// Redirect user to notificaciones.php
document.location = '/notificaciones.php';
}
});
// Prevent link click doing anything
return false;
}
I must to check the result of Ajax are same with some PHP variable value.
Is there anyway to do this?
Thank you in advance for help.
My Ajax HTML:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){
echo $x;
}
?>
<a id="input" href="#">Get value<input type="hidden" value="2_2_1_3"></a>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function(){
$("#input").on("click", function(){
$.ajax({
type: 'POST',
url: "ip2.php",
data:'ip=' + $(this).parent().find('input').val(),
success: function(data){
$("#ip").html(data);
}
});
});
});
</script>
The PHP script:
<?php
if($_POST['ip'] >= 0){
$ip = $_POST['ip'];
echo $ip;
}
?>
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){ // this will never be true because $x is diferent of $y
echo $x; //so you will never print this out
}
And you won't have the element with id="ip" to print the result from your ajax
success: function(data){
$("#ip").html(data);
}
For it to work try this:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
echo $x;
?>
I'm not entirely sure what you want to do, but you can always send your post data as an object in javascript, for simplicity you can use the post function.
Example:
$.post( "ip2.php", { ip: $(this).parent().find('input').val() }, function( data ) {
console.log( data );
});
More info:
https://api.jquery.com/jquery.post/
https://api.jquery.com/jQuery.ajax/
Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.
Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}