I am using wordpress ajax and following code not passing parameter value metakey: id to $_POST["metakey"]. So var_dump($_POST) shows array(0) { }
if I enter static value of variable in PHP function $key=<any meta key> then its works fine
jQuery(".selectbox").change(function(){
var id = this.id;
// do a POST ajax call
$.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ({
action: "get-mata-value",
metakey: id
}),
success: function( response ) {
jQuery.each(response ,function(index,value){
jQuery('#' +id).append('<option value="'+value+'">'+value+'</option>');
});
}
});
});
PHP:
add_action("wp_ajax_get-mata-value", "get_mata_value");
add_action("wp_ajax_nopriv_get-mata-value", "get_mata_value");
function get_mata_value()
{
global $wpdb;
$key=$_POST["metakey"];
$result=
$wpdb->get_col( $wpdb->prepare(
"
SELECT DISTINCT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
",
$key
) );
return($result);
exit();
}
Did you try this?
data: (JSON.stringify({
action: "get-mata-value",
metakey: id
})),
Related
I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
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 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 :-)
I like to make an advertisement base on the visitor state/region. And also to display language based on visitor country.
I am trying to get data from this website and works well in ( only displaying the output) :
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// example where I update content on the page.
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
}
} );
of course this will give the visitor state data on browser :
<div id="region-name"></div>
Problems :
How can I get the id output save in php string.
I want to ave it to database using PDO prepare statement.
I have tried to save it by doing:
$state='<div id="region-name"></div>';
$pages->testsavestate($state); // save to database PDO
public function testsavestate($state) {
$ses_id = session_id();
$country='mycountry';
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES
(?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
It didn't save the state result, but only the above the tag.
Thanks
In order for that data to travel from your first AJAX call to get location values. You can also call another ajax on top of that to your PHP processing. Consider this example:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
// after your .html() below
// after your successful ajax outside, call your php file
var country = location.country_name;
var state = location.region_name;
// call your php file
jQuery.ajax({
url: 'index.php', // <-- name of the php file that will handle such request
type: 'POST',
dataType: 'JSON',
data: { country: country, state: state },
success: function(response) {
alert(response);
}
});
}
});
Then on your php file, process the values
if(isset($_POST['save'])) {
$country = $_POST['country'];
$state = $_POST['state'];
$ses_id = session_id();
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES (?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try {
$query->execute();
if($query->rowCount() > 0) {
echo "Save complete!";
exit;
}
} catch(PDOException $e){
die($e->getMessage());
}
}
I have a php page generating and displaying a table. for the last row in the table i want to display an image with an 'onclick' function attached. this will send the username for the selected row to a script that will use AJAX to update a database. The table displays fine but the AJAX is not working. my php to display the image is:
echo "<td> <img id='tblimg'
onclick='like('" . $row['Username'] . "')'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
<script type="text/javascript" >
function like(user)
{
$.ajax(
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
);
}
</script>
And here is update.php:
<?php
$con=mysqli_connect("","sam74","********","sam74");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Username = $_POST['username'];
$Liked = $_POST['liked'];
$sql = "UPDATE 'followers' SET 'Liked' = '$Liked' WHERE 'Username' = '$Username'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
There are some mistakes in this code, let me help you line by line.
echo "<td> <img id='tblimg'
onclick=\'like('" . $row['Username'] . "');\'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
Escape your quotes for the onclick event first
function like(user)
{
$.ajax({
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
});
}
add { and } to the ajax call
Remove the quotes from table name and fields
$sql = "UPDATE followers SET Liked = '$Liked' WHERE Username = '$Username'";
in ajax success and after the function begins, you can always print a message to see if your function is being called, and if php script is returning some error, use an alert for that
UPDATE
success: function(data){
alert(data); // this will print you any php / mysql error as an alert
}
UPDATE 2
Write your onclick option like this.
echo "<img onclick=\"like('" . $row['Username']. "');\"
src='like.jpg' alt='like/dislike image'
width='80px' height='30px' />";
The jQuery.ajax() function expects an object to be passed; you need to use { and } to begin and end your object literal. What you currently have is invalid JavaScript syntax, if you checked your browser's developer tools you'd see an error indicating that. So:
$.ajax(
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
);
should be
$.ajax({ // added {
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
}); // added }