Passing array from PHP to jQuery in wordpress - php

I have been struggling with this for a while. There are tons of topics on the subject but none is actually working for me, but being a newbie might be the cause so please elaborate.
I simplified the code and it won't work, I posted the code below
I am queering the Database, and saving the values to an array in a function
I then need to pass that array to a jquery in the same function. I used json_encode but i am getting this error:
Uncaught SyntaxError: Unexpected token <
Here is the code:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = <?php echo json_encode($PHPArray); ?>;
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}

Change it to this:
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = ".json_encode($PHPArray)."; //Notice the change here
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}

You have to escape the string correctly:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = " . json_encode($PHPArray) . ";
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}

If you put PHP inside JavaScript the PHP part is only text, do this:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = " . json_encode($PHPArray) . ";
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}

At least from what is shown, neither $i nor $PHPArray are initialized. PHP can be messy about these things, but you cannot directly refer to indexes of non-existent arrays, or variables that have not been declared.
I'll guess the token error was from your browser trying to deal with the text output of a PHP error being flushed, along the lines of 'undefiend' or 'undefined index.'
Also, the real (or at least convenient) purpose of the foreach construct is not fooling with indexes. Try the following substitute for your current loop:
$PHPArray = array(); // $PHPArray = [];
if($query1){
foreach($query1 as $q){
$PHPArray[] = $q->element_value;
}
}
Beyond that, "wpdb" suggests calls related to specific frameworks, but in case this is a mysqli_stmt call, i believe the call is singular: get_result.

Related

php script error: no search results or error displayed on the search query

I'm working on a php project and the search function from the database is not returning any results or any error. Below is the code for the search function:
function searchweb() {
console.log("click");
//e.preventDefault();
searchWebsite = $("#searchWebsite").val();
if (searchWebsite == "")
$("#searchWebsite").focus();
else {
console.log("else");
$("#search").html("Searching..");
$("#search").attr("disabled", true);
var excat = "like";
if ($('input[type=checkbox]').prop('checked'))
excat = "match";
$.post("userinput.php", {
searchWebsite: $("#searchWebsite").val(),
excat: excat
}, function (data) {
console.log("hey"+data);
populateSearch(data);
});
function populateSearch(data){
data = JSON.parse(data);
$('#result').empty();
$.each(data, function (key, value) {
//console.log(data);
$('#result').append("<tr>\
<td><a href='"+value.website_name+"' target='_blank'><i class='glyphicon glyphicon-search'></i></a></td>\
<td>"+value.website_name+"</td>\
<td>"+value.avg_score+"</td>\
<td><img class = 'imgs img-responsive center' src='../img/"+value.remark+".png' alt ='"+value.remark+"' />\
</td></tr>");
});
}
// console.log(searchWebsite);
$("#search").html("Search Website");
$("#search").attr("disabled", false);
}
}
The 'searchweb' function calls the post method to search in the mysql database. I'm using phpmyadmin for this project. The code for post function in userinput file:
if(isset($_POST['searchWebsite'])){
$searchWebsite = $_POST['searchWebsite'];
$type = $_POST['excat'];
$sql = "SELECT * from websites WHERE ";
//for excact match
if($type=="match")
$sql.= "MATCH(tags) Against('$searchWebsite') ORDER BY avg_score DESC";
//for tags contaionun gthose words
else
$sql.= "tags LIKE '%$searchWebsite%' ORDER BY avg_score DESC";
$result = mysqli_query($db, $sql);
if($result){
$rr = array();
$i=1;
while($row = mysqli_fetch_assoc($result))
{ $rr[] = $row;
$i=$i+1;}
echo json_encode($rr);
}
else
{
echo "<script type='text/javascript'>alert('Error: '".mysqli_error($db).");</script>";
}
}
No error will be spit back as this is a .post in javascript call / AJAX request. AJAX will not dynamically parse the javascript error code you're trying to trap within the AJAX request.
It's better to do something like this:
PHP side:
Replace:
echo "alert('Error: '".mysqli_error($db).");";
With:
echo json_encode( [ 'error' => mysqli_error($db) ] );
Javascript Side:
// Note you shouldn't have to parse JSON since on the PHP side the error array has been encoded as json
if( ! $.isEmptyObject(data.error) ) {
alert( data.error );
}

how do i get a date value from php into a jquery variable?

<?php
$sql = "SELECT * FROM expense WHERE userid = $userid";
$expense_date= array(); //array declared to be used below
$amount = array();// array declared
$result = mysqli_query($conn, $sql);
if(!$result){
die("query failed"); // query failed due to no connection or error in query
} else {
while( $row = mysqli_fetch_assoc($result)){ // fetches infromation
array_push($amount, $row["amount"]); //pushes my distances whic are returned from the query from the database into an array
$date_entered = ( date("d-n-y", strtotime($row["timestamp"])));
array_push($expense_date, $date_entered);//pushes date travelled
}
}
//$arr = array('distance'=>$dist_covered, 'dateTravel'=>$travel_date);
//print_r(json_encode($arr)); ------ make sure distance are being inserted into the database
echo $date_entered; ?>
<script type="text/javascript">
var unavailableDates = <?php print_r(json_encode($date_entered))?>;
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}
else {
return [false, "", "Unavailable"];
}
}
$(function() {
$( "#Datepicker1" ).datepicker({
numberOfMonths:2,
beforeShowDay: unavailable
});
});
</script>
I am trying to get the unavailableDates variable to pick out a date from the database. the variable which is in php is echoing out the date in the same format. but the variable is not recognizing it. If i enter the dates manually it works.
var unavailableDates = <?php echo json_encode($date_entered)); ?> || '';
Both print_r() and var_dump() are used to display data for debugging purposes. print and echo are used for outputting strings. Using echo is most common.
$d = date("d-n-y");
print_r($d);
var_dump($d);
echo $d;
Will produce:
11-2-16
string(7) "11-2-16"
11-2-16
So, even though you're using print_r() instead of echo, the result is the same output. This is because it's a string variable in this case. Or is this an array of dates?
You may have another issue in your code. Are you getting any console errors?
I may be missing something. Is unavailableDates supposed to be an array of dates? In that case, you might have your variables mixed up a bit. See the array_push() PHP function.
See
http://php.net/manual/en/function.array-push.php
array_push($expenseDates, $date_entered);//pushes date traveled
Then...
var unavailableDates = <?php echo (!empty($expenseDates)) ? json_encode($expenseDates) || []; ?>;
Right, your code here is a bit of a mess to be honest, lots of obvious issues which I have corrected below:
<?php
$sql = "SELECT * FROM expense WHERE userid = $userid";
$expense_date = array(); //array declared to be used below
$amount = array(); // array declared
$result = mysqli_query($conn, $sql);
if (!$result) {
die("query failed"); // query failed due to no connection or error in query
} else {
while ($row = mysqli_fetch_assoc($result)) {
$amount[] = $row["amount"];
$date_entered = date("d-m-y", $row["timestamp"]); #CORRECTED - ONLY FEED IN THE TIMESTAMP
$expense_date[] = $date_entered;
}
}
//echo $date_entered; #WHY IS THIS BEING ECHOED OUT HERE FROM PHP?
?>
<script type="text/javascript">
var unavailableDates = '<?= $date_entered ?>';
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}
else {
return [false, "", "Unavailable"];
}
}
$(function () {
$("#Datepicker1").datepicker({
numberOfMonths: 2,
//beforeShowDay: unavailable # WHAT IS THIS?
beforeShowDay: unavailable('MISSING_DATE')
});
});
</script>
Is this all happening in 1 .php file?
Look in the datepicker code - looks like that is meant to be a call to the unavailable() .js function? What date is that meant to call?

Passing js variables to php using jquery

I'm trying to do a realllly simple post of a javascript variable to a php file.
Jquery bit in keyinput.php:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
PHP bit in viewcomic.php:
include './scripts/keyinput.php';
$JSIndex = $_POST['variable'];
echo "Index = " . $JSIndex;
//$JSIndex should be equal to the javascript variable imgIndex... but it outputs nothing
Any thoughts would be extremely helpful! I'm trying to get my comics website to go live.
Thanks!
Your logic is wrong: at the moment you define your key variable, e is undefined. Then you attach your event handler inside an if statement that will always evaluate to false so that will never work.
The assignment to key should be inside your event handler and the conditional needs to go, you already have that inside your event handler.
Edit: you should also only do your ajax call if one of your action keys is pressed (put it inside the event handler) and do something with the result.
Edit 2: Checkout the manual on $.post, you should add a callback function to process the return value of your php script.
For example:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);

Pagination algorithm with javascript

I have a javascript function which makes an ajax request to php controller method which returns a JSON encoded array.
function initGallery(offset) {
if(offset === undefined)
{
var request_url = url+'avatar/gallery';
} else {
var request_url = url+'avatar/gallery/'+offset;
}
$('#avatar_gallery').html('')
$.get(request_url,function(data) {
var dat = jQuery.parseJSON(data);
//Build gallery
$('#avatar_gallery').html('<div class="gallery_box"></div>');
$('.gallery_box').append('<div class="gallery_header">Your Avatar Gallery</div>');
$('.gallery_box').append('<div class="gallery_container"></div>');
$.each(dat.avatars,function(index,item)
{
$('.gallery_container').append(
'<div class="gallery_item">'+
'<img src="'+item.avatar_src+'" id="'+item.avatar_id+'" onclick="avatar.view_avatar(this.id)"/>'+
'</div>'
);
});
$('.gallery_box').append('<div class="gallery_footer"></div>');
$('.gallery_footer').html('<div class="gallery_pagination"><div>');
});
}
And this is my controller method
function gallery($offset= 0)
{
$limit = 12;
$user_id = $this->session->userdata('user_id');
$data = $this->avatar_model->user_avatars($user_id,$limit,$offset);
$avatars = array();
$count = $this->avatar_model->count_user_avatars($user_id);
$pages = ceil($count/$limit);
foreach($data as $key => $avatar)
{
$dat['avatar_id'] = $avatar->avatar_id;
$dat['avatar_src'] = $avatar->avatar_small;
$dat['create_date'] = time("d-m-Y",$avatar->create_date);
$avatars[] = $dat;
}
$server_response['avatar_count'] = $count;
$server_response['avatars'] = $avatars;
echo json_encode($server_response);
}
I dont really have an idea on how to paginate the data returned from the reques.
Please point me in the right direction
It's easy. Add a class to your pagination link (you can use full_tag_open and full_tag_close config variable: <p class="pagination> and </p>).
After that you can redefine the .pagination a click event (I'm using JQuery):
function () {
$(".pagination a").click(function(event){
event.preventDefault();
YourJSFunction($(this).attr("href"));
});
}
I hope this helps you.

Problem with $.getJSON in jquery

My Jquery code
function nalozi() {
var id_skupine = $('#skupina option:selected').val();
$('#artikel option').remove();
//$('#artikel').append('<option value="'+id_skupine+'">'+id_skupine+'</option>');
$.getJSON('artikli.php', {id_skupine:$('#skupina').val()}, function(data) {
$.each(data, function(index,item) {
$("#artikel").append("<option value=" + item.id + ">" + item.ime_artikla + "</option>");
});
});
}
$(document).ready(function() {
nalozi();
$('#skupina').change(function() {
nalozi();
});
});
AND PHP CODE
<?php
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
for ($i=0;$i<$velikost;$i++)
{
$elements[]=mysql_fetch_assoc($poizvedba);
}
}
echo json_encode($elements);
?>
I don't get the values back.
Update:
You should never put variable before sanitalizing/validating/type-converting into your sql queries. If your the value you expect in query string is a number, you need to properly type-cast it like this:
$id_skupine = (int) $_GET['id_skupine'];
And if it is a string, the least you can do is to use mysql_real_escape_string function:
$str = mysql_real_escape_string($_GET['str']);
Shouldn't you be grabbing the records from db like this:
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
while($row = mysql_fetch_assoc($poizvedba)){
$elements[] = $row['ime_artikla'];
}
}
echo json_encode($elements);
Might be your query is not returning anything
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
Remove single quote from '$id_skupine'
Try
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '".$id_skupine."'");

Categories