How to structure jquery ajax to be flexible to in and outputs? - javascript

I have a one-page structured website. I am trying to use Ajax to update my data on user demand.
I am trying to figure out how to structure my ajax code, so that it will be flexible to my in and outputs = I want to run different function depending on the clicked link, and I want to return the right output to the right div.
HTML links:
<a href="#page-a" class="dbLink" data-variable="funcA">
<a href="#page-b" class="dbLink" data-variable="funcB">
<div id="page-a">
<div id="a-result"></div>
</div>
<div id="page-b">
<div id="b-result"></div>
</div>
JS, ajax (I am passing a data-variable along the link to controle the action):
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
dataType: 'json',
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
});
});
functions.php:
include 'dbconnect.php';
function funcA($mysqli){
$result = $mysqli->query("select * from database");
$row = mysqli_fetch_assoc($result);
echo $row['column'];
}
function funcB($mysqli){
$result = $mysqli->query("select * from database2");
$row = mysqli_fetch_assoc($result);
return $row['column'];
}
if (isset($_POST['action'])) {
$resp = null;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#page-a";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#page-b";
break;
default:
break;
}
echo json_encode($resp);
}

add another data-* variable set to the id of the place you want to output the data. To control the format of the returned data provide the dataType option in the ajax options, and of course make sure the pointed to url actually outputs that type of data. dataType It will tell jQuery how to parse the incoming data.
var theContainer = $(this).attr("data-container");
...
dataType:"json" //or text, or xml etc etc
success: function(data){
//if data is upposed to be json
//and datType is set to json
//data will be an object, same with xml
//process data how you need to
$("#"+theContainer).html(whateverYouHaveDone);
}
If you need to control the target of the returned data within your php script then turn your returned data into json and send the selector for the target to it
$resp = new stdClass;
switch($_POST['action']) {
case "funcA":
$resp->data = funcA($mysqli);
$resp->target = "#someContainer";
break;
case "funcB":
$resp->data = funcB($mysqli);
$resp->target = "#someContainer";
break;
default:
break;
}
echo json_encode($resp);
Then in your ajax success
success: function(resp){
if(resp.data){
$(resp.target).html(resp.data);
}
}
And of course set dataType:"json"
To return just the mysql row, do the same thing as above but in the ajax success resp.data will be an object. So just access the properties of resp.data with the column names of the row
success: function(resp){
if(resp.data){
//if say you have a column named "username"
var username = resp.data.username;
}
}

$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var target = $(this).attr('href');
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(data){
$(target).html(data);
}
});
});

there are many ways to do this.
I see you have understood the custom data-* attributes. I would add one more attribute: data-target=""
<a href="#page-a" class="dbLink" data-variable="funcA" data-target="a-result">
<a href="#page-b" class="dbLink" data-variable="funcB" data-target="b-result">
<div id="page-a">
<div class="a-result"></div>
</div>
<div id="page-b">
<div class="b-result"></div>
</div>
Then inside your JQuery, you do like you do with your data-variable, only that you add the new data-* attribute:
$(document).on("click", ".dbLink", function(e) {
e.preventDefault();
var theAction = $(this).attr("data-variable");
var theTarget = $( this ).attr("data-target");
$.ajax({
url: 'ini/functions.php',
data: { action: theAction },
type: 'post',
success: function(){
/* Here you have to change the data[] to match the JSON return from your PHP-script. You can of course do it without JSON, but I would use http://www.php.net/manual/en/function.json-encode.php on an array from PHP.*/
$("input[class="+ theTarget +"]").html( data["foo"][0]["bar"] );
}
});
});
If you want to play with a real life example, I made this fiddle for another guy on stack overflow a while back: http://jsfiddle.net/Olavxxx/Mu66h/
Put a number in the left box (like 5006), it's postal codes. The target then is the postal adress in the right input box. The concept is very much the same as you are after, with data-targets.

Related

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

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();
}

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

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