I realize this has been asked numerous times here, but I just can't figure it out. I'm certain it is simple, but I've been banging my head a little. I have search results that are php arrays, displayed in a jquery window. I need to eventually get them back to the server, but first need to pass them to jquery variables. This is where I am stuck.
You will see I have made an attempt to via $book_title, trying to pass that to a jquery variable "title"
<script>
$(function() {
$( "#dialog" ).dialog({
height: 550, width: 450});
$( ".btn" ).click(function(){
//assign values to each variable
//var title = $("#returnvalues").val();
var title = <?php echo json_encode($book_title);?>;
var author = $("#returnvalues").val();
var published = $("#returnvalues").val();
var description = $("#returnvalues").val();
var pages = $("#returnvalues").val();
var publisher = $("#returnvalues").val();
var ISBN = $("#returnvalues").val();
//book_title = $item['volumeInfo']['title'];
$.ajax({
type: "POST",
url: 'book-meta.php',
dataType: 'json',
//assign values to the variables to be passed to the server via data
data: { title : title, author : author, published : published,
description : description, pages : pages, publisher : publisher, ISBN : ISBN},
success: function(data)
{
//alert(data);
//identify the variables for unique handing on the server side
$("input[name='bbp_topic_title']").val(data.title);
$("input[name='bbp_extra_field1']").val(data.author);
$("input[name='bbp_extra_field2']").val(data.published);
$("input[name='bbp_extra_field3']").val(data.description);
$("input[name='bbp_extra_field4']").val(data.pages);
$("input[name='bbp_extra_field5']").val(data.publisher);
$("input[name='bbp_extra_field6']").val(data.ISBN);
//$("#displayResults").html(data);
},
error: function(errorThrown){
alert('error');
}
});
$( "#dialog" ).dialog( "close" );
});
});
</script>
<strong><p style="font-size: 16px; text-align: center";>Top 10 Results for "<?php echo #$_POST['q']; ?>"</p></strong>
<strong><p style="font-size: 14px; text-align: center";>choose a book to select as your topic</p></strong>
<table style="width:400px">
<col width="325">
<col width="75">
<?php $i=0; foreach ($data['items'] as $item) { $i++; ?>
<tr>
<td>
<strong><u><div style="font-size: 14px";><?php printf($item['volumeInfo']['title'])?></u></div></strong>
<strong>Author: </strong><?php printf( $item['volumeInfo']['authors'][0])?><br />
<strong>Published: </strong><?php printf( $item['volumeInfo']['publishedDate']); ?><br />
<strong>Page(s): </strong><?php printf( $item['volumeInfo']['pageCount']); ?><br />
<strong>Publisher: </strong><?php printf( $item['volumeInfo']['publisher']); ?><br />
<strong>Category: </strong><?php printf( strtolower($item['volumeInfo']['printType']).', '.strtolower($item['volumeInfo']['categories'][0])); ?>
<strong>ISBN: </strong><?php printf( $item['volumeInfo']['industryIdentifiers'][0]['identifier']); ?></td>
<td><p><input type="submit" method="post" name="selectbook" value="Select" class="btn" id="returnvalues" /></p>
<img src="<?php printf( rawurldecode($item['volumeInfo']['imageLinks']['smallThumbnail'])); ?>" />
</td>
<tr><td style="width:420px"><p><strong>Description: </strong><?php printf( $item['volumeInfo']['description']); ?><br /></p></td>
<?php $book_title=$item['volumeInfo']['title'];
//$book_meta=array($item['volumeInfo']['title']=>"$book_title",$item['volumeInfo']['authors'][0]=>"$book_author");
//print(json_encode($book_meta));
Any help is appreciated. If this gets marked as a duplicate question, please also give this newbie some specific direction. Thanks.
I figured this out! Thanks to XQDev and Uttara for the help! I had to create a separate script, within the loop where my php results are displayed. In this separate script I declare my javascript variables only.
<script>
var title = <?php echo json_encode($book_title); ?>;
</script>
Issue is resolved! Hopefully this thread will help someone in the future with a similar issue.
var title = "<?php echo $book_title; ?>" could cause your wanted result.
The result can be checked by using alert(title) after the assignment.
Your variable are no "jQuery Variables", by the way. They are ordinary Javascript variables. But you pass and access them by using jQuery methods.
But: Your way, in case $book_title contains a string, should be fine, too.. What exactly isn't working?
If you are trying to assign php array to javascript variable then do this
var title = <?php echo json_encode($book_title); ?>;
considering that your $book_title is an array
Eg: <?php
$book_title = array('one', 'two');
?>
javascript: title = ['one', 'two']
Related
I am trying to create a very basic auction page on a site I am working on. I'm sort of working it out as I go along but I am now a bit stuck.
Data is stored in a MySQL table, this data has the image link, the ID, and the current bid.
I then retrieve the data in PHP/HTML, example here:
$result = mysqli_query($con,"SELECT * From auction WHERE category = 'Bathroom' ORDER BY ID DESC");
while($row = mysqli_fetch_array($result))
{
echo "<form name='auction' id='auction'><div class='auction-thumb'>
<div class='auction-name'>" . $row['Item'] . "</div>";
echo "<img class='auction' src='" . $row['ImagePath'] . "' />";
echo "<div class='auction-bid'>Current Bid: £" . $row['CurrentBid'] . "</div>";
echo "<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>";
echo "<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>";
echo "<div class='auction-bid'><button name='submit' id='submit' value='" . $row['ID'] . "' type='submit'>Place Bid!</button></div>";
echo "</div></form>";
}
echo "</table>";
This code pulls through the items absolutely fine. Along with a textbox for a name and a bid (I am not doing anything with the name at the moment).
My jQuery then looks like this:
$(document).ready(function(){
$('#auction').submit(function(){
var id = $('#submit').val();
var bidname = $('input[name=bidname]').val();
var bid = $('input[name=bid]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return true;
});
});
Again this is very basic and I am not concerned about validation just yet.
And finally here is a snippet of my PHP code:
$bidname = $_POST['bidname'];
$bid = $_POST['bid'];
$id = $_POST['id'];
$query = "UPDATE auction SET CurrentBid = '$bid' WHERE ID = '$id'";
mysqli_query($con, $query) or die(mysqli_error());
mysqli_close($con);
My problem is that when I click submit, nothing really happens. All the variable names and values get put into the browser address bar, and the page just seems to refresh.
The data does not get posted and when I debug with Firebug, I just get a red cross and it doesn't give me any errors.
I know from just looking at my code that best practices aren't followed, but I just want to get something working and then tidy it up later.
If anyone could point me in the right direction that would be a big help.
Thank you, and if you need anymore information please just let me know.
First of all: You need to rewrite your form element every element should have an unique id to differentiate the respective element.
<?php while($row = mysqli_fetch_array($result)){ ?>
<form name='auction' id='auction<?php echo $row['ID'] ?>'>
<input type='hidden' name='id' value='<?php echo $row['ID'] ?>'>
<div class='auction-thumb'>
<div class='auction-name'><?php echo $row['Item'] ?></div>
<img class='auction' src='<?php echo $row['ImagePath'] ?>' />
<div class='auction-bid'>Current Bid: £<?php echo row['CurrentBid'] ?></div>
<div class='auction-bid'>Your Name: <input type='text' class='bidder' name='bidname'/></div>
<div class='auction-bid'>Your Bid: <input type='text' class='auction-text' name='bid'/></div>
<div class='auction-bid'>
<input type='submit' name='submit' value='Place Bid!'>
</div>
</div>
</form>
and replace your jquery code to
$(document).ready(function(){
$('form[name="auction"]').submit(function(){
var id = $(this).find('input[name="id"]').val();
var bidname = $(this).find('input[name="bidname"]').val();
var bid = $(this).('input[name="bid"]').val();
$.ajax({
type: "POST",
url: "auction-handler.php",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
success: function(){
}
});
return false;
});
});
You need to re-write this a bit: ID's have to be unique and when you loop through your items you assign the same IDs over and over to elements in different forms.
So when you try to get the values in your submit handler, jQuery does not know which value to get (it probably gets the value of the first element with that ID).
You should start with changing the IDs to for example classes and then serialize (for example...) the submitted form - $(this) in your submit handler - to get the correct data.
Add following keys in ajax to trace the errors.
$.ajax({
url: "auction-handler.php",
type: "POST",
dataType: "json",
data: {bidname: bidname, bid: bid, id: id},
crossDomain:true,
success: function(result){ console.log(result); }
error: function(httpReq,status,exception){
alert("error - " +status+" "+exception);
}
});
This is my script:
<script>
$(document).ready(function(){
$("#ID_Blangko").on("change", function() {
var blangko = $("#ID_Blangko").val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah';
$.ajax({
url: baseUrl,
data: {nama : blangko},
dataType: "json",
success: function(datas){
$("#Jumlah_Blangko").val(datas);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#Jumlah_Blangko').val("some error.");
}
});
});
});
</script>
and this is my controller code:
public function ajax_jumlah($nama)
{
$this->db->select('Jumlah_Blangko');
$this->db->where('Nama_Blangko', $nama);
$result = $this->db->get('tb_blangko');
$amount = $result->row()->Jumlah_Blangko;
return json_encode($amount, JSON_NUMERIC_CHECK);
}
i've double checked the onchange function and controller function is working well and returning value. The problem is I cant pass this value to my ajax code and print it on input form. Here's my html:
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="row">
<div class="col-md-6">
<?php
$atribut_blangko = 'class="form-control" id="ID_Blangko"';
$selectedBlangko = $values->ID_Blangko;
echo form_dropdown('ID_Blangko', $dropdown_Blangko, $selectedBlangko, $atribut_blangko);
?>
</div>
<div class="col-md-6">
<?php echo form_input('Jumlah_Blangko', '', 'id="Jumlah_Blangko" class="form-control" placeholder="Jumlah" maxlength="50" readonly="true"') ?>
</div>
</div>
<?php echo form_close() ?>
update #2 and this solve my problem
this the controller function im accessing directly from browser URL that is http://localhost/amc/program/administrasi/blangko_rusak/ajax_jumlah/Malaysia
and i found out that
return json_encode($amount, JSON_NUMERIC_CHECK); this doesnt work and then i changed to:
echo json_encode($amount, JSON_NUMERIC_CHECK); this work.
I dont know how this is possible, anyone can explain?
Please check the line no 3 in your code it should be "$("#ID_Blangko").val()" instead of "$("#ID_Blangko").val"
Explanation:
in the above code line you were expecting to get the value of the element having id "ID_Blangko" and you are using the jQuery, but the main thing here is that the "val" is a function and not a variable so you can not access the value by just saying "$("#ID_Blangko").val" because it looks for a property named as 'val'
I think
var blangko = ID_Blangko.value;
should be
var blangko = $('#ID_Blangko').val();
or
var blangko = $(this).val();
EDIT
Your problem with controller/action not seeing the variable could be because it expects params instead of query string vars like most frameworks do. Something like this could help you with that
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah/' + blangko;
I'm trying to send AJAX data to my wordpress table but all I can get from my PHP is a 0. Its on the admin side. Can anyone help me?
Also all of this code is inside my plugin-admin.php file inside my plugin folder.
<?php
if ( ! defined( 'ABSPATH' ) || ! current_user_can( 'manage_options' ) ) exit;
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<script>
jQuery(document).ready(function($) {
var spostsarray = new Array();
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: "POST",
action: "featured_submit_action",
data: {"posts": spostsarray},
success: function(data){
console.log(data);
}
});
});
});
</script>
I've condensed it a bit but the general idea is that I can grab all the recent posts and the user can select which ones they want to feature, send that to the PHP method and edit the table with it.
The problem is with my AJAX callback I only ever return 0 and not the data sent from the javascript.
SOLVED:
After some help from Rohil_PHPBeginner I figured it out. The reason it didn't work is that I was executing the code from the menu page at at that point it was too late to add a hook. Here is the page I used to solve it:
AJAX in WP Plugin returns 0 always
Below code worked perfectly fine for me:
<?php
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<?php
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
add_action( 'wp_ajax_nopriv_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<script>
jQuery(document).ready(function($) {
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
});
});
</script>
You don't need to pass the AJAX url in that way because when I used your code, it is showing me with PHP. WordPress provides a default url for AJAX so you can use that( ajaxurl which I used in below code).
Other than that You have not added code for no-privilege user (if it is going to use only for privileged user then it is okay otherwise you need to add code for that).
WordPress returns 0 when an ajax call doesn't find a valid callback function (though the 0 could be return from many other things).
WordPress looks for callbacks matching wp_ajax_{callback} when a user is logged in and wp_ajax_nopriv_{callback} when the user is logged out. {callback} is populated with the POST'd value of the "action" hidden input. Note that you're not passing the action into your AJAX call. You should change:
data: {"posts": spostsarray},
to
data: data
Since you're not going to match a callback function without passing in action, WordPress is returning 0
I have a question which is probably easy to solve but due to my lack of javascripting skills I find it rather hard.
I am using a function to auto-complete database info in a search bar. For that I'm using this javascript function:
<script type="text/javascript">
$(function(){
$(".search").keyup(function(){
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!=''){
$.ajax({
type: "POST",
url: "http://marceldepender.nl:2222/CMD_FILE_MANAGER/domains/marceldepender.nl/public_html/Recap/wp-content/themes/radiate/templates/search.php",
data: dataString,
cache: false,
success: function(html){
$("#divResult").html(html).show();
}
});
}
return false;
});
jQuery("#divResult").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
$('#inputSearch').click(function(){
jQuery("#divResult").fadeIn();
});
});
</script>
As you can see in the first part of the function, there is a value called url: this url includes (at least I think that is what it does) a certain php page when the if statement is true. This php page (search.php) does a query and gives output related to the search terms.
Though for some reason, the javascript function doesn't go to that search.php page. I have done / tested several things:
IN the original document the url was just plan: url: "search.php", - I changed it to the entire link where the search.php is on though since the previous url didn't work (the new one doesn't either though).
I changed the search.php to some easy echo code just so I know the page is being included / redirected to.
For some reason (and I think it is because the search.php isn't being included) the code doesn't work.. The page where the javascript function is on, is located on a directadmin files on the net, the search.php is also located in this same map.
So the question is: why isn't my search.php included and how can I fix this?
For some better understanding of my search.php code I inserted the original code below:
<?php
include('includes/db.php');
if($_POST){
$q=$_POST['searchword'];
$sql_res=mysql_query("select uid,username,email,media,country from test_auto_complete where username like '%$q%' or email like '%$q%' order by uid LIMIT 5");
while($row=mysql_fetch_array($sql_res)){
$username=$row['username'];
$email=$row['email'];
$media=$row['media'];
$country=$row['country'];
$b_username='<b>'.$q.'</b>';
$b_email='<b>'.$q.'</b>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="display_box" align="left">
<img src="<?php echo $media; ?>" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $country; ?></span></div>
<?php
}
}
?>
Can anyone help advise why this setTimeout() function is not working? I have tried many version over the net and it is still not working.
<script type="text/javascript">
function makeSlection(frm, proj, tenure, address, postal, cat, parent, estate, latlng, district, state) {
alert(proj);
alert('hello im inside makeselection function');
opener.projectn.value = proj;
opener.tenure.value = tenure;
opener.address.value = address;
opener.postcode.value = postal;
opener.category.value = parent;
opener.category.onchange();
opener.state.value = state;
opener.region.value = estate;
opener.add.value = latlng;
opener.latlngse.click();
//setTimeout(function(){alert('hi');},3000);
setTimeout(function(){ pelay(cat); },5000);
}
function pelay(cate){
alert(cate);
opener.category_id.value = cate;
this.close;
}
</script>
<body>
Please select project name.
<form id="fsrm" name="fsrm" action="#">
<table width="100%">
<?php
for($i=0;$i<count($prolists);$i++){
$row = $prolists[$i];
?>
<tr>
<td>
<button type="submit" name="nselect<?php echo $row->id ?>" id="nselect<?php echo $row->id ?>" value="<?php echo $row->project_name ?>" onclick="JavaScript:makeSlection(this.form, document.getElementById('nselect<?php echo $row->id ?>').value, '<?php echo $row->tenure ?>', '<?php echo $row->address ?>', '<?php echo $row->postal_code ?>', '<?php echo $row->cat ?>', '<?php echo $row->parent_id ?>', '<?php echo $row->estate ?>', '<?php echo $row->lat ?>,<?php echo $row->lng ?>', '<?php echo $row->district ?>', '<?php echo $row->state ?>');">Select</button>
</td>
<td>
<?php echo $row->project_name ?>
</td>
</tr>
<?php } ?>
</table>
</form>
</body>
Even when I try this:
setTimeout(function(){alert('hi');},3000);
It's also not working.
Just added the body codes to call the javascript.
Short Answer
It does work. Something else must be going wrong for you.
Long answer
First of all, mixing HTML/Javascript/PHP like that makes it a lot harder for anyone to understand what the hell your code is trying to achive.
Secondly, your question stands a better chance of getting an answer that will help you progress to a solution if you make it Short, Self Contained, Correct, and add an Example.
Preferably one we can view online which demonstrates the simplest version you could create that is working (or in this case broken).
Such a version would look something like this:
<script>
function makeSlection(cat) {
alert('hello im inside makeselection function');
setTimeout(function(){ pelay(cat); },1500);
}
function pelay(cate){
alert(cate);
}
</script>
<button onclick="JavaScript:makeSlection('foo');">Select</button>
I took the liberty of creating an example on JsFiddle from the code you provided us with.
Which leads me to the third point: the simplified version of the code you gave us in your question works. Both alerts get triggered.
So I'm guessing we are not getting the full picture here.
Your setTimeout is inside the makeSelection function so it will only set the timeout once the makeSelection function is executed.