how to get exact answer from ajax? - php

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

Related

Ajax call to PHP action/function with array as data (in wordpress)

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

Get JQUERY function return in PHP

I want to know if I can get the return of a JQUERY function, in PHP ?
I have this following jquery function, returning an array and I want to get this array in my PHP, in order to send it to process the data
function getItemMetaList() {
var itemMetaArray = [];
$('.frm_pro_form input, .frm_pro_form select, .frm_pro_form textarea').each(function(cpt){
if($(this).attr('type') != 'hidden' && ($(this).attr("type") != "submit")) {
console.log(cpt);
console.log($(this).attr("name"));
itemMetaArray.push($(this).attr("name"));
}
});
return itemMetaArray;
}
Thanks in advance
function getItemMetaList() {
var itemMetaArray = [];
$('.frm_pro_form input, .frm_pro_form select, .frm_pro_form textarea').each(function(cpt){
if($(this).attr('type') != 'hidden' && ($(this).attr("type") != "submit")) {
itemMetaArray.push($(this).attr("name"));
}
});
$.ajax({
method: "POST",
url: "some.php",
//data: { array: itemMetaArray}
data: JSON.stringify({ array: itemMetaArray})
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
you can send data by this way in a php file like documented here: ajax jquery
The Ajax request returns data for JavaScript in the page loaded in your browser. The browser does not display the data automatically. The answer is captured by .done() in MacBook's example. You can put JavaScript in the done () method to display the data returned. If you wish the page to reload in your browser, Ajax is not the good way. In JavaScript, use form.submit instead. Then you can have your PHP code read the submitted data and generate a new html page and have this displayed by the browser.

how to implement onclick for php button

I have a line in a php code that reads something like this:
echo '<div class="sample-button">Do something</div>'
This shows a clickable text link on the page. Now I want that clicking on this link should call a php function myFunc() which I have defined in the same php file. How do I implement this?
Whatever the <a href="#"> gos to is your answer.
The path needs to be <a href="#?call=1">
Now that's set, you need to create an if statment..
if ($_GET['call'] === 1){ myFunc(); }
When you click the link, it should refresh the page with the url now set to: localhost/page.php?call=1. As the php page is refreshed it can call MyFunc().
You can call a JS function on click, not a php one. I think you have to better check the documentation on what is the purpose of the php language.
If you really want to execute a php script by clicking on the link you can use jquery ajax.
In your case call the same php file where the function is located by listening to the button's click event and perform the ajax request:
$('.sample-button').click(function() {
// Ajax Call
$.ajax({
url: "/path_to_your_script.php",
contentType: "application/x-www-form-urlencoded",
type: "POST",
data: {callFunction:true},
success: function(response){
// Check your response
},
error: function(){
// Error handling
}
});
});
On top of your php script you need to check:
<?php
if (!empty($_POST['callFunction'])) {
your_function() {
return $yourResponse;
}
exit();
}
A quick example ( untested ) to show how you might invoke your php function and use the response after clicking a standard link on a page.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) && $_POST['action']=='call_my_func' ){
/* ensure we discard the buffer if we need to send a response */
ob_clean();
function myFunc($var){
echo 'PHP function...';
}
/* call your function */
call_user_func( 'myFunc', 'some variable' );
exit();
}
?>
<script type='text/javascript'>
function invoke_myfunc(){
var http=new XMLHttpRequest();
http.onreadystatechange=function(){
if( http.readyState==4 && http.status==200 ) alert( http.response );
};
var headers={
'Content-type': 'application/x-www-form-urlencoded'
};
http.open('POST', document.location.href, true );
for( header in headers ) http.setRequestHeader( header, headers[ header ] );
http.send( [ 'action=call_my_func' ].join('&') );
}
</script>
<?php
/*
in your page
-------------
*/
echo '<div class="sample-button">Do something</div>';
?>

Need a few pointers on AJAX in Wordpress

Alright, so I'm trying to learn how to work with AJAX in Wordpress the "right way", via admin-ajax, etc. but I'm kinda going around in circles. I want to load a portfolio item (custom post type) via Ajax - when I do it via jQuery .load() it works fine, but as soon as I try to do it the Wordpress way, it doesn't. Tutorials and StackOverflow questions have only been helpful up to a certain point... I don't know, I just feel kinda dense :-(
This is how far I've gotten, with a little (ahem) tutorial help here and there. Forgive me if there are stupid errors, for I am terrible with this kind of code. It's new to me and all. Also, thanks in advance for any help you can offer :-D
The jQuery:
jQuery(document).ready(function ($) {
$(".getworks").click(function (event) {
event.preventDefault();
if (getpost !== '') {
$.ajax({
type: "POST",
url: MyAjax.ajaxurl,
data: {
'action': MyAjaxRequest,
'getpost': $(this).attr('href'),
},
success: function (data) {
// This outputs the result of the ajax request
$('#portfolio-back').html(data);
console.log(data);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
});
});
The PHP:
add_action( 'wp_ajax_MyAjaxRequest', 'MyAjaxFunction' );
add_action( 'wp_ajax_nopriv_MyAjaxRequest', 'MyAjaxFunction' );
function MyAjaxFunction() {
if ( isset($_POST['getpost']) ) {
$getpost = $_POST['getpost'];
if ( $getpost !== '' ) {
echo $getpost;
}
}
die();
}
UPDATE: So I added a preventDefault to the click and I $(this).attr('href') into the ajax call, and now the URL is loaded into the DIV on success, instead of the actual contents.

Passing AJAX GET results to location

Here's my problem
<script type="text/javascript"><!--
$('#button-confirm').bind('click', function() {
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bitcoinpayflow/confirm',
success: function(url) {
location = '<?php echo $continue;?>';
}
});
});
//--></script>
The url returns this:
https://bitcoinpayflow.com/ordersArray // note the lack of space between orders and array. Is this a problem? If it is, I can get it to display in JSON notation with some fiddling.
(
[order] => Array
(
[bitcoin_address] => 1DJ9qiga2fe94FZPQZja75ywkdgNbTvGsW
)
)
Now, what I want to do is append the entry bitcoin_address to $continue '<?php echo $continue;?>'. which stands for: /index.php?route=checkout/success. so it would read /index.php?route=checkout/success&btc=1DJ9qiga2fe94FZPQZja75ywkdgNbTvGsW. it seems like it should be simple but I can't see how to do it.
The next page has a javascript function that parses the bitcoin address from the url and displays it on the page. This all works fine, I just can't get the bitcoin address to actually show!
Make it return JSON. You will reduce the amount of pain a lot. Apparently it's PHP, so just use PHP's json_encode(), then just use the JSON response to concatenate stuff to url in your 'success' function.
location = "<?php echo $location; ?>&btc=" + data.bitcoin;
...or something like that. Try console.log(data) if you're not sure what you're getting.
Set a variable in global scope and then access it within functions
<script type="text/javascript"><!--
var btcaddress = null;
$('#button-confirm').bind('click', function() {
if( isValidBtcAddress( btcaddress ) ){
Url = 'index.php?route=payment/bitcoinpayflow/confirm' + btcaddress;
}else{
Url = 'index.php?route=payment/bitcoinpayflow/confirm';
}
$.ajax({
type: 'GET',
'url': Url,
success: function(url) {
location = '<?php echo $continue;?>';
}
});
});
function someotherFunction( response ){
btcaddress = response['order']['bitcoin_address'];
}

Categories