Simplify my Jquery xajax like function - php

Basically I was trying to replicate one of the things that xajax gave me with Jquery -> The ability to define what my response modifies server side without setting anything up client side. Works perfectly as is, but each time I want to call a different Jquery function, I have to add it to my if statements.
Each element in the response array contains something to be changed client side.
I should be able to take out almost all of the this.action == 'blah' if statements and replace with some clever javascript, but apparently I'm not clever enough. :)
$.showMessage is simply my replacement for alert, with a timeout and sticky bit.
My client Jquery function:
$.doAjax = function(func,values) {
$.ajax({ data: values, url: '/time/ajax/' + func, type: 'POST', dataType: 'json', timeout: 5000,
error: function(xhr, ajaxOptions,thrownError){ $.showMessage('Error processing request: ' + func,10000);$('#debug').html(xhr.responseText); },
success: function(data){
if(data){
$.each(data, function(){
if ( this.action == 'attr' ) $(this.target).attr(this.content);
if ( this.action == 'removeAttr' ) $(this.target).removeAttr(this.content);
if ( this.action == 'addClass' ) $(this.target).addClass(this.content);
if ( this.action == 'removeClass' ) $(this.target).removeClass(this.content);
if ( this.action == 'html' ) $(this.target).html(this.content);
if ( this.action == 'text' ) $(this.target).text(this.content);
if ( this.action == 'val' ) $(this.target).val(this.content);
if ( this.action == 'eval' ) {
try {
eval(this.content);
}
catch(err) {
$.showMessage(err,5000);
};
};
});
}
}
});
return this;
};
My server side code:
header("Content-type: text/plain");
$response = array();
$response[] = array('action'=>'html','target'=>'#booked_time_group_unbilled','content'=>get_booked_time_group_unbilled());
$response[] = array('action'=>'html','target'=>'#booked_time_my_unbilled','content'=>get_booked_time_my_unbilled());
$response[] = array('action'=>'eval','target'=>'','content'=>"$.showMessage('The selected time has been deleted',5000,true)");
echo json_encode($response);

This should work:
$(this.target)[this.action](this.content);

I'm not exactly sure what you're asking? Stylistically, I would write it like this:
var handlers = {
attr: function() { $(this.target).attr(this.content) },
removeAttr: function() { $(this.target).removeAttr(this.content) },
// etc.
};
$.each(data,function() {
handlers[this.action].call(this);
});
If you just want to execute whatever the server sends back, which not just always send back an eval action?

Related

why WP Ajax data printed in the console instead of the page

this the first function of the Ajax call runs on focusout woocommerce input fields with check_country_fees action and url '<?php echo admin_url('admin-ajax.php'); ?>' so how to pass the returned data and passing them as arguments normally?
function addEvtListenerToCheckoutPage()
{
?>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", (event) => {
$(document).ready(function() {
document.getElementById('billing_first_name').addEventListener("focusout", function() {
alert("Hello World!");
if (document.getElementById('billing_first_name') !== "") {
var billing_first_name = document.getElementById("billing_first_name").value;
alert("testajax");
var data = {
action: 'check_country_fees',
billing_first_name: document.getElementById("billing_first_name").value
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
if (response.success == true) {
// Handle Success
// let resp = JSON.parse(response.data.json_response);
if (response.success) {
alert(response);
console.log(response);
alert(response);
alert("Sucess");
// Hanle Success Response
}
} else {
console.log(response);
console.log(data);
alert("Sucess");
}
}).fail(function(response) {
// Handle Error
console.log("failing");
console.log(response);
alert("FAIl");
});
}
});
});
});
// document.getElementById("#billing_first_name").addEventListener("input", myFunction);
</script>
<?php
?>
<script language="javascript">
alert("sended addevent");
</script>
<?php
}
when I run the action call function add_action('wp_ajax_check_country_fees', 'testing_ajax_action'); the result printed in the browser console like that
</script>
<script>
alert("sended datasuccess");
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
testing ajaaaaxnullArray
(
[action] => check_country_fees
[billing_first_name] => Stevea
)
Stevea</br>
<script>
alert("test ajaxbilling name");
</script>
SteveaArray
(
)
Receiving data function
function testing_ajax_action()
{
echo "testing ajaaaax";
if (isset($_POST['billing_first_name'])) {
$billing_first_name = $_POST['billing_first_name'];
$billing_first_name = json_decode($billing_first_name);
extract($_POST);
print_r($_POST);
$billing_first_name2 = json_decode($_POST['billing_first_name_post']);
//testingajax($billing_first_name);
testingajax($billing_first_name);
} else {
return 0;
}
}
You need to send the data back from the backend to the frontend.
Here is a crude basic diagram of an ajax request:
Event → JS request → PHP Processing → PHP Response → JS Handling
If you're not sending any data with your PHP response then you can't handle it on the front end.
You can use wp_send_json_success() and wp_send_json_error() to send the appropriate response success/error status and attach to it any relevant data you want to handle on the front end.
By convention, the PHP Processing function is usually anonymous.
From a security standpoint you should implement a nonce system too. You can refer to the following answer about using Ajax the right way in WordPress.
Coming back to your problem, you can pass an array through wp_send_json_success.
<?php
add_action( 'wp_ajax_{$action}', function () {
if ( check_ajax_referer( '_ajax_nonce' ) ) {
//...
$data = array(
'timestamp' => time(),
'key' => 'value',
//...
);
wp_send_json_success( $data );
} else {
wp_send_json_error();
};
} );
On the javascript handling side, you would intercept it and do something with it:
$.ajax({
//...
success: ( response ) => {
console.log( response.data );
//...
},
//...
});

how to get exact answer from ajax?

I have some ajax requests in my jquery code. and my php server should decide what to do. but I'm beginner in web programming I don't know how to return the exact response .
<script>
$(document).ready(function () {
$('#subButton').click(function () {
var query = "query";
$.ajax({
type: 'POST',
url: 'info.php',
datatype: 'text',
data: {query: query},
complete: function (data) {
alert(data);// it returns the whole php page!
}
})
.done(function (data) {
alert("done");
})
.fail(function () {
alert("Posting failed.");
});
});
});
</script>
and there is my php code
<?php
if ( isset( $_POST[ 'music' ] ) ) {
echo "music";
}
if ( isset( $_POST[ 'query' ] ) ) {
echo "query";
}
if ( isset( $_POST[ 'url' ] ) ) {
echo "url";
}
?>
in this jquery I want just the word "query" not whole page. and also I want to know how to set it in html through some tags.
so we've found out why your php page is returning the whole script. It had a .html extension, not a .php one. Without the php extension the server would just send back the whole lot.
how to put it into a tag? Quite easy.
suppose you have a tag on your page like this (note the id):
<h2 id="main_heading">some heading</h2>
all you need to do is ask jquery to place the response inside it like this.
complete: function (data) {
// select the object with the right ID and change its innerHTML
$('#main_heading').html(data);
}
this will replace the contents of the <h2> with whatever comes back.
update
if youre having trouble, try putting a console.log call in and check it with the browsers javascript console, this should show you whats being sent back from the server.
like this:
complete: function (data) {
console.log(data);
// select the object with the right ID and change its innerHTML
$('#main_heading').html(data);
}

Use parts of AJAX response in different divs

I want to send this AJAX request:
function sumMonthly() {
var cur_month = $('#month option:selected').attr("value");
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
data: {action: ["get_sum_income", "get_sum_expense", "get_cash_remaining"], cur_month:cur_month}
});
request.done(function(response){
$('#sum_income').html('<h1 class="positiveNum float-right">$' + response.get_sum_income + '</h1>');
$('#sum_expense').html('<h1 class="float-right">$' + response.get_sum_expense + '</h1>');
});
request.fail(function(jqxhr, textStatus){
alert("Request failed: " + textStatus);
});
};
and somehow access the return response, but I'm not sure how to access only a certain part of the response and put it in one div, then put another part in another div. Here's some of my PHP:
if(isset($_POST['action']) && in_array("get_sum_income", $_POST['action'])) {
//do stuff here, put result in $i;
if(!empty($i)) {
echo $i;
} else {
echo '$0.00';
};
};
This is not a real "answer" to your problem, but I can't write what I want in a comment.
You'll need to work on your PHP to consolidate the code and make an array something like this:
$json = array
(
'varname1' => $variable1,
'varname2' => $variable2,
'varname3' => $variable3,
'varname4' => $variable4,
'varname5' => $variable5
);
$jsonstring = json_encode($json);
echo $jsonstring;
Then on client side you can do something like:
.done(function(response) {
$('#div1').text(response.varname1);
$('#div2').text(response.varname2);
$('#div3').text(response.varname3);
$('#div4').text(response.varname4);
$('#div5').text(response.varname5);
});
Again, this is not a specific solution, but it should get you started.
I always write my php, then run it without the client, grab the output on the screen and submit it to jsonlint.com to make sure it's json.

jQuery $.post Callback Function (data) is Undefined

I submit a form using jQuery to a php file on my server.
Everything works... (the php file gets the right post variables, makes a database entry etc.)
But on the response, sometimes 'data' goes wacky.
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
if ( data.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
}, "json");
});
php script returns (on success)
$response['status'] = 1;
$response['message'] = 'worked';
echo json_encode($response);
exit();
I'm getting a whole lot of crap, and not enough awesome sauce.
Does anyone have an idea why sometimes 'data.status' is undefined, and sometimes it isn't?
Try it like this>
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
var obj = jQuery.parseJSON(data);
if ( obj.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
});
});
How does exit() behave with regards to output buffering? Does it flush the output buffer?
try this one:
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize())
.success(function(){
alert('awesome sauce');
}).error(function(){
alert('crap');
});
});

Prevent stacking of AJAX-requests

I've got a problem which I can't seem to solve.
I'm currently implementing a an AJAX-function similar to the one Twitter uses - that fetch new posts on scrolling.
The jQuery looks something like this:
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
$('div#ajaxloader').show();
$.ajax({
url: "loader.php?lastid=" + $(".container:last").attr("id"),
success: function(html){
if(html){
$("#main").append(html);
$('div#ajaxloader').hide();
}else{
$('div#ajaxloader').html('No more posts to show.');
}
}
});
}
});
Now the problem; if the user scrolls really fast and the database is doing it's work quickly - the jQuery doesn't seem to be able to send the correct id as a query fast enough - which results in double-posts.
Anyone have a good idea on how to prevent this?
Try This:
var runningRequest = 0;
$(window).scroll(function(){
if(runningRequest <1){
if($(window).scrollTop() == $(document).height() - $(window).height()){
runningRequest++;
$('div#ajaxloader').show();
$.ajax({
url: "loader.php?lastid=" + $(".container:last").attr("id"),
success: function(html){
runningRequest--;
if(html){
$("#main").append(html);
$('div#ajaxloader').hide();
}else{
$('div#ajaxloader').html('No more posts to show.');
}
}
error: function(){runningRequest--;}
});
}
}
});
I would set a boolean to true right before making my request, and whenever the request completes I'd set it back to false. Then I'd wrap the code that makes the request in a check for whether that value is true or false. I'd also add a bool that tells me whether I should even bother making a request--no sense in requesting if the last request came back empty (unless, perhaps, the data set could change since the last request). Either way, here's the code I'd start with:
( function( global )
{
var $ = global.jQuery,
$win = $( global ),
$doc = $( global.document ),
$ajaxLoader = $( 'div#ajaxloader' ),
$main = $( '#main' ),
requestInProgress = false,
outOfPosts = false;
$win.scroll( function()
{
if( ! requestInProgress &&
! outOfPosts &&
$win.scrollTop() === $doc.height() - $win.height()
)
{
requestInProgress = true;
$ajaxLoader.show();
$.ajax( {
url: 'loader.php',
data: {
lastid: $( '.container:last' ).attr( 'id' )
},
success: function( html )
{
if( html )
{
$main.append( html );
$ajaxLoader.hide();
}
else
{
outOfPosts = true;
$ajaxLoader.html( 'No more posts to show.' );
}
},
complete: function()
{
requestInProgress = false;
}
} );
}
} );
}( window ) );

Categories