Passing AJAX GET results to location - php

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'];
}

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

how to post a persian statement with spaces in ajax url

I have used ajax as below:
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var valueSelected = valueSelected.replace(/ /gi,"%20");
var valueSelected = encodeURIComponent(valueSelected);
//alert(valueSelected);
$.ajax({
type: 'post',
encoding:"UTF-8",
url: "<?php echo base_url();?>Search/cities_of_province/"+valueSelected,
data: '',
contentType: "charset=utf-8",
success: function (result) {
//alert(result);
$('.city').html(result);
return false;
}
});
return false;
});
valueSelected in above url is a persion statement with space in it. for example it is استان آذربایجان شرقی.
when it is post to the url, just first part(استان) is recieved.
I aslo removed valueSelected.replace(/ /gi,"%20") and encodeURIComponent(valueSelected) but nothing happend.
what is the solution?
I faced no issue like that.. I used no encodeURIComponent no encoding:"UTF-8" no contentType: "charset=utf-8"
Nothing needed. And it works simply perfect. I tested it with following code
I have Html
<input id='yourInputId' value='استان آذربایجان شرقی' />
JavaScript
<script>
var valueSelected = $('#yourInputId').val();
//before ajax request
alert(valueSelected ); // it gives me here =>استان آذربایجان شرقی
//before making ajax reuest plz confirm you get above value correctly here
alert(<?php echo base_url();?>); //it must be valid as well
$.ajax
({
type: "POST",
url: "<?php echo base_url();?>Search/cities_of_province", //should be valid
data: { province : valueSelected },
success: function (result) {
alert(result); //it gives => استان آذربایجان شرقی
},
error:function(a)
{
alert(a.responseText);
}
});
</script>
PHP
<?php
if(isset($_POST['province']))
$v = $_POST['province'];
else
$v = 'Province value not provided from client side';
echo $v;
?>
So it looks like you are using a select input here. If that is the case, you should use alphanumeric/ASCII value key in your options and not the human readable labels. That might look like:
<option value="some_ascii_key">استان آذربایجان شرقی</option>
You can then have a reliable key to use in your AJAX request.
I also think your request should be a GET and not a POST since you are just reading values from API rather than trying to create/update records via API.
Putting it all together, you might have something like this:
// note values for each property/ley may not be important here
// as they are not really needed to validate that the province key
// in option value has not been modified by client,
// which is really what you are using this for.
// If you need to have option label text available in
// javascript you can store that here as shown.
var provinceConfiguration = {
'key1': 'استان آذربایجان شرق';
'key2': 'some other Persian string';
// and so on...
}
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
// perhaps validate that value provided is amongst expected keys
// this used the provinceConfiguration object proposed in this example
if(typeof provinceConfiguration[valueSelected] === 'undefined') {
console.log('Unexpected province key passed');
e.stopPropagation();
return false;
}
// probably can drop this line if defined keys do not need encoding
var valueSelected = encodeURIComponent(valueSelected);
// since you can use default GET setting you can use this shorthand
$.get(
'<?php echo base_url();>Search/cities_of_province/' +
valueSelected,
function(result) {
// console.log(result);
$('.city').html(result);
return false;
}
);
/*
Or more verbose option
$.ajax({
type: 'GET',
// not valid setting key -> encoding:"UTF-8",
url: '<?php echo base_url();>Search/cities_of_province/' + valueSelected,
// default is fine here so not needed -> contentType: "charset=utf-8",
success: function (result) {
// console.log(result);
$('.city').html(result);
return false;
}
});
*/
return false;
});
Note that you should be using console.log() to debug code rather than alert(), as alert actually blocks code execution and may make some debugging more problematic as your debugging mechanism changes how your code executes. This can problem can be exacerbated when debugging asynchronous code.
Your server-side code would obviously need to be updated to understand the province keys as well.
Please take a look at this javascript library. That can be of help to you.
Fix Persian zero-width non-joiner(Replace spaces by half-space)
import { halfSpace } from "persian-tools2";
halfSpace("نمی ‌خواهی درخت ها را ببینیم؟") // "نمی‌خواهی درخت‌ها را ببینیم؟"
Fix Persian characters in URL.
import { isPersian, toPersianChars } from "persian-tools2";
URLfix(
"https://fa.wikipedia.org/wiki/%D9%85%D8%AF%DB%8C%D8%A7%D9%88%DB%8C%DA%A9%DB%8C:Gadget-Extra-Editbuttons-botworks.js",
); // "https://fa.wikipedia.org/wiki/مدیاویکی:Gadget-Extra-Editbuttons-botworks.js"
URLfix("https://en.wikipedia.org/wiki/Persian_alphabet"); // "https://en.wikipedia.org/wiki/Persian_alphabet",
URLfix("Sample Text"); // "Sample Text"

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.

Ajax return value with return not work

I have 2 files(call.php and post.php) and using ajax pass value from call to post,and i want to get return value from post ,but this doesn't work. when i change post ,modify "return" to "echo",it works,but i don't know why.can anybody give me a help?
Examples would be most appreciated.
call.php
<script type="text/JavaScript">
$(document).ready(function(){
$('#submitbt').click(function(){
//var name = $('#name').val();
//var dataString = "name="+name;
var dataPass = {
'name': $("#name").val()
};
$.ajax({
type: "POST",
url: "post.php",
//data: dataString,
data: dataPass,//json
success: function (data) {
alert(data);
var re = $.parseJSON(data || "null");
console.log(re);
}
});
});
});
</script>
post.php:
<?php
$name = $_POST['name'];
return json_encode(array('name'=>$name));
?>
update:
by contrast
when i use MVC "return" will fire.
public function delete() {
$this->disableHeaderAndFooter();
$id = $_POST['id'];
$token = $_POST['token'];
if(!isset($id) || !isset($token)){
return json_encode(array('status'=>'error','error_msg'=>'Invalid params.'));
}
if(!$this->checkCSRFToken($token)){
return json_encode(array('status'=>'error','error_msg'=>'Session timeout,please refresh the page.'));
}
$theme = new Theme($id);
$theme->delete();
return json_encode(array('status'=>'success'));
}
$.post('/home/test/update',data,function(data){
var retObj = $.parseJSON(data);
//wangdongxu added 2013-08-02
console.log(retObj);
//if(retObj.status == 'success'){
if(retObj['status'] == 'success'){
window.location.href = "/home/ThemePage";
}
else{
$('#error_msg').text(retObj['error_msg']);
$('#error_msg').show();
}
});
This is the expected behaviour, Ajax will get everything outputted to the browser.
return only works if you are using the returned value with another php variable or function.
In short, php and javascript can't communicate directly, they only communicate through what php echoed or printed. When using Ajax or php with javascript you should use echo/print instead of return.
In Fact, as far as I know, return in php is not even used in the global scope very often (on the script itself) it's more likely used in functions, so this function holds a value (but not necessarily outputs it) so you can use that value within php.
function hello(){
return "hello";
}
$a = hello();
echo $a; // <--- this will finally output "hello", without this, the browser won't see "hello", that hello could only be used from another php function or asigned to a variable or similar.
It's working on the MVC framework because that has several layers, probably the delete() method is a method from the model, which returns its value to the controller, and the controller echo this value into the view.
Use dataType option in $.ajax()
dataType: "json"
In post.php try this,
<?php
$name = $_POST['name'];
echo json_encode(array('name'=>$name));// echo your json
return;// then return
?>

Categories