Ajax Call in Javascript Function On Button Click - javascript

I am getting an error in this code which says Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick.I cannot figure out where i am going wrong.
Here is my code which contains a while loop which fetches data from the database and $xyz goes to the javascript function called myFunction().
Here is my file:
if($rs->num_rows>0)
{
while($row=$rs->fetch_object())
{
$xyz=$row->judged_id;
$my="SELECT DISTINCT first_name,picture from user1 where id='$xyz'";
$hj=$con->query($my);
if($hj->num_rows>0)
{
while($rz=$hj->fetch_object())
{
echo $name=$rz->first_name;
$pic=$rz->picture;
echo"<img src='$pic' height=100 width=100>";
?>
<button type='button' class='egf' onClick="myFunction('xyz')">Chat</button>
<br><br>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var xyz=<?php echo $xyz; ?>;
function myFunction('xyz')
{
$.ajax({
type: 'GET',
url: 'chat/public/01_index.php?id2=xyz',
success: function(data) {
$('.chat-list').html(data);
}
});
});
}
</script>
<?php
}
}

What is the content of the PHP variable $xyz? If it is a string, for example,
this:
var xyz=<?php echo $xyz; ?>;
Would result in a JavaScript like:
var xyz=ABCDEFG;
Which is not valid. Instead it should then be:
var xyz = '<?php echo $xyz; ?>';
Furthermore your function defintion seems not right, should be something like this instead, since you can not specify a string as a parameter name:
function myFunction(varNameHere)
{
alert(varNameHere);
}
Click me
Also you are using jQuery ready() function inside your function, which will probably not fire at anytime.
I think what you are looking for is something like this:
function myFunction(xyz)
{
$.ajax({
type: 'GET',
url: 'https://httpbin.org/get?q=' + xyz,
success: function(data) {
$('.chat-list').html(data.args.q);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
<div class="chat-list">
</div>

First of all: you don 't need jQuery. The jQuery library is just a wrapper written in native javascript. It would be more performant to use native javascript.
After that as I mentioned in the comments, you should use a click event listener on the parent element, which contains all your buttons. Just have a look at the following example.
<div class="parent-element">
<?php
while ($row = $resource->fetch_object())
{
echo '<button id="' . $row->id . '">' . $row->title . '</button>;
}
?>
</div>
<script>
var parent = document.querySelector('.parent-element'),
xhr = new XMLHttpRequest();
parent.addEventListener('click', function( event ) {
let target = event.target;
if (target.tagName.toLower() == 'button' && target.id) {
// your xml http request goes here
xhr.open('GET', yoururl + target.id);
xhr.onload(function() {
if (xhr.status === 200) {
// do something with the response
let response = xhr.responseText;
}
});
xhr.send();
}
}, true);
</script>
The while loop adds the buttons to your HTML markup. Further a click event listener was added to the parent div element. On every click it checks, if the target element is a button and if this button has an id attribute. If so an asynchronous request is executed.

Related

Wordpress get current page name or id within ajax request callback

I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "notes_select_page"
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
I took the request from action hook.
add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
And the callback i used several code but doesn't work. Try 1.
public static function select_page(){
global $pagename;
die($pagename);
}
Try 2
public static function select_page(){
global $wp_query;
$pagename = get_query_var( 'pagename' );
if ( !$pagename) {
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
die($pagename);
}
Try 3
public static function select_page(){
global $post;
die($post->ID);
}
But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
You don't need ajax for this.
Add this function to your code.
You can now get the page id by using:
var id = get_current_page_id();
To retrieve the post details you have to send the data yourself
data:{
action: "notes_select_page",
post_id: current_post_id, //current_post_id should either parsed from DOM or you can write your ajax in PHP file
}
You can either use a hidden box for current post id and get in the Js file using class or id or write the ajax in you php file itself.
Then you can retrieve via POST
public static function select_page(){
$post_id = $_POST['post_id'];
}
I'm getting post ID from the default WordPress post editing form, like so :
var post_ID = jQuery('[name="post_ID"]').val()*1;
Tje *1 converts the ID into an integer, otherwise it's interpreted as a string.
First take page id by this function
either
<div id="current_page_id"> <?php get_the_ID(); ?> </div>
or
<body page-id="<?php get_the_ID(); ?>">
Now In jquery ajax take following
var page_id = $('current_page_id').html();
OR
var page_id = $('body').attr("page-id");
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "pageid="+page_id,
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
There is a solution to solve the issue in Wordpress. Adding ajax code in wp_footer hook, where using php code current page id can be retrieved and pass as ajax value.
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):
<?php
echo '<input type="hidden" name="activepost" id="activepost"
value="'.get_the_ID().'" />'
;?>
Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/

how can I make one button correspond to different clicked div html jquery php?

You can see my code below. I face a challenge that I don't know how to use one button to correspond different click. On the php, if I put the button inside the foreach loop, it will create a lot of button, that's not what I want. In the js, if I put the on.click button inside the foreach elements loop, it will also create a lot of on.click button, so I click one button, it will run many times depends on the number of label_name. I think about addClass, if I clicked the heart div, I use js to add a class, and then get the attr('id') inside button.on.(click), so I can differentiate them in my server php and mysql can request the correspond data. But the problem is that if a user click every div, then every div add classes, then problem again.
var current_page = 1;
var elements_body = {
"heart": "1",
"eye": "2",
"ear_nose_throat": "3",
"hand_foot_mouth": "4"
};
jQuery.each(elements_body, function (label_name, label_num) {
var disease_label = $('#' + label_name + '_d');
disease_label.on('click', function () {
var data = {
action: 'body_part_keyword', //wordpress loading url
postSearchNonce: MyAjaxSearch.postSearchNonce,
current_page: current_page,
label_name: label_name //this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type: 'POST',
cache: false,
data: data,
success: function (data) {
disease_menu_result.append(data);
current_page++
}
}); //ajax
});
}); //jQuery.each
$('#loadmorebutton_body').on('click', function () {
//I dont know how can I make this button to correspond above code
});
<div id="disease_menu">
<?php
$arr = Array(
'heart'=>'heart',
'eye'=>'eye',
'ear_nose_throat'=>'ear nose throat',
'hand_foot_mouth'=>'hand foot mouth'
);
foreach ($arr as $key=>$value) {
?>
<div class="disease_li" id="disease_li_<?php echo $key;?>">
<span class="disease_span" id="<?php echo $key;?>_d"><label>(<?php echo $value;?>)</label>diseases</span>
</div>
<!--disease_li-->
<?php }?>
</div>
<!--disease_menu-->
<button id="loadmorebutton_body">Load More</button>
Use javascript functions :
function MyFunction() {
jQuery.each( elements_body, function( label_name, label_num) {
var disease_label= $('#'+ label_name + '_d');
disease_label.on('click',function(){
var data={
action: 'body_part_keyword',//wordpress loading url
postSearchNonce : MyAjaxSearch.postSearchNonce,
current_page:current_page,
label_name:label_name//this label_name will differentiate data that need to request from mysql in the action.php
};
$.ajax({
url: MyAjaxSearch.ajaxurl,
type:'POST',
cache: false,
data: data,
success: function(data){
disease_menu_result.append(data);
current_page++
}
});//ajax
});
});
}
$('#loadmorebutton_body').on('click',function(){
MyFunction();
}

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

JQuery Functions loading prematurely

What my aim here is when a button is pressed, it replaces the content of the div with a textbox and a button. And when the button is pressed, it posts the text to a script, which handles the request and stores the inputted data from the textbox into the database.
It is then set to call another function called Reset(); which is supposed to restore the old contents of the div. However, the idea that I had in mind it calls the DB Query to find what's CURRENTLY in the database. But, it's not doing that, it's just getting the old value. Which makes me think that the function is running at the start of the page, and not when it is called.
It definitely updates the value because when I refresh the value is updated. Here's my code:
<script>
$(function () {
$('#button').on('click', function(e) {
var myVar = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<div class='span12'><h2>Revision Notes</h2><form id='revisionnotes' name='revisionnotes' method='POST'><textarea style='width:100%;height:290px; padding:10px;' id='notes' name='notes'>" + myVar + "</textarea><br/><button onclick='Button();' name='submit' id='submit' class='btn btn-primary'>Change Revision</button></div></form></div>");
});
});
function Reset() {
var myVar2 = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<h2>What's new?</h2><div class='well'>" + myVar2 + "</div><input type='button' value='Change Revision' id='button' name='button' class='btn btn-primary'>");
});
function Button() {
$('#revisionnotes').on('submit', function(e) {
var data = $(this).serialize();
$.ajax({
type: 'post',
url: 'submits/updatenotes.php',
data: data, // $('form').serialize(),
success: function (data, textStatus, jqXHR) {
Reset();
alert("Delta - POST submission succeeded");
}
});
e.preventDefault();
});
}
</script>
Is there any way to stop the function from retrieving the value from the database until it is called from the Success of the Button function?
Many thanks, Jarrod.
$(function () {
$('#button').on('click', function(e) {
var myVar = <?php echo json_encode($db->result("SELECT * FROM revision_notes", "notes")); ?>;
$('#WCTarget').html("<div class='span12'><h2>Revision Notes</h2><form id='revisionnotes' name='revisionnotes' method='POST'><textarea style='width:100%;height:290px; padding:10px;' id='notes' name='notes'>" + myVar + "</textarea><br/><button onclick='Button();' name='submit' id='submit' class='btn btn-primary'>Change Revision</button></div></form></div>");
});
});
this is not "exactly" a function, it is a closure around a piece of code that runs only once, onload of page.
If u want to load a changing value from your server, you would need to use AJAX, same as u use for the data submission.

submitting form with parameter from a link in jquery

I am trying to save data in database in background through a link, and to give download functionality to that link in front end. but it gives an error.
my script is -
<script>
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(me);
});
function saveData(me){
$.ajax({
type: "POST",
url: "download_counter.php",
data: { client_id: "<? echo $client_id;?>", candidate_id: me }
});
}
});
</script>
this is the link (It looks fine)
<button name="download"></button>
download_counter.php looks like -
<?
if (isset($_POST['candidate_id'])) { // Form has been submitted.
$candidate_id = $_POST['candidate_id'];
$client_id= $_POST['client_id'];
$date = date("Y-m-d");
echo "client - ".$client_id;
echo "candidate - ".$candidate_id;
$query = "INSERT INTO `downloads`(`client_id`, `candidate_id`, `download_date`) VALUES ('".$client_id."', '".$candidate_id."', '".$date."')";
$result = mysql_query($query);
}
?>
when i click the link, it lets download the file but database do not updates.
Please help.
There is an error with passing parameter to function saveData, so your ajax request not occur:
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(data); // was me
});
Check jquery click event handler, which says
// say your selector and click handler is somewhat as in the example
$("some selector").click({param1: "Hello", param2: "World"}, some_function);
// then in the called function, grab the event object and use the parameters like this--
function some_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
database is updating now, but it is not getting value of candidate_id.
i did this -
<script>
$(document).ready(function(){
$("#download").click(function(){
$("#count").hide();
var me = $(this), data = me.data('params');
saveData(data); // was me
});
function saveData(data){
$.ajax({
type: "POST",
url: "counter.php",
data: { client_id: "2", candidate_id: data.ca_id }
});
}
});
</script>
I think on click the data you are reading is a string and in the given format.
And you are passing that as data, but since it is not an valid id,
that value in the database is not updated.
Check this out

Categories

Resources