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.
Related
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' );
I'm trying to make a like/dislike button in ajax. The ajax is sending my data to a separate file where it is saved in a database and that file sends back the successful response {"status":"success","message":"Like has been saved.","data":{"like":"1"}} that I got from the chrome network response window. However the code in $ajax(...).done isn't working
I have console.logged and var.dumped every bit of code i possibly could. my data IS being sent to my database which should mean that the SQL and the like class is correct. I've also tried simply console.log 'ging the response "res" and putting the rest in comments, but that again gives me nothing
<div>
Like
Dislike
<span class='likes' data-id="<?php echo $post->id ?>"><?php echo $post->getLikes(); ?></span> people like this
</div>
$("a.like, a.dislike").on("click",function(e){
var postId = $(this).data("id");
if($("a.like")){
var type = 1;
}else if($("a.dislike")){
var type = 0;
}
var elLikes = $(this).siblings(".likes");
var likes=elLikes.html();
$.ajax({
method: "POST",
url: "ajax/postlike.php",
data: {postId: postId, type:type},
dataType: "json",
})
.done(function( res ) {
console.log(res);
if(res.status=="succes"){
console.log(res);
if(res.data.like=="1"){
likes++;
elLikes=html(likes);
$("a.like").css("display","none");
$("a.dislike").css("display","inline-block");
} else if(res.data.like=="0"){
likes--;
elLikes=html(likes);
$("a.dislike").css("display","none");
$("a.like").css("display","inline-block");
}
}
});
e.preventDefault();
});
if(!empty($_POST)){
try {
$postId=$_POST['postId'];
$type=htmlspecialchars($_POST['type']);
$userId=$_SESSION['user_id'];
$l = new Like();
$l->setPostId($postId);
$l->setUserId($userId);
$l->setType($type);
$l->save();
$res = [
"status" => "success",
"message" => "Like has been saved.",
"data" =>[
"like" => $type
]
];
}catch (trowable $t) {
$res = [
'status' => 'failed',
'message' => $t->getMessage()
];
}
echo json_encode($res);
var_dump($res);
}
what I expected to happen was that Ajax sent the JSON data to the php code, that put it in a database, which works. Then gives a successful response to the Ajax, also works. The Ajax would then switch out the like/dislike buttons whilst adding or taking 1 like from the span "likes". It however does absolutely nothing
I'm almost 100% certain that the problem is something stupid that I'm overlooking, but i really can't find it.
Typo in 'success' in on line: if(res.status=="succes"){
you can try with this:
error: function(xhr, status, error) {
console.log(error)
},
success: function(response) {
console.log(response)
}
in your Ajax function, to know what happen in the server side with the response.
If you specify a return data type for the ajax request to expect, and the actual returned value isn't what you specified, then your error/fail function will be triggered if you have one. This is because adding dataType: "json" causes you're ajax try and parse your return value as json and when it fails, it triggers your error handler. It's best to omit the dataTaype and then add a try catch with JSON.parse in your done function, to get around this.
E.G
.done(function (string_res) {
console.log(string_res);
try {
var json_obj = JSON.parse(string_res);
console.log(json_obj);
} catch (e) {
console.log('failed to parse');
}
// do work/operations with json_obj not string_res
})
.fail(function (jqXHR, textStatus) {
console.log('failed')
});
For some reason, I need to pass an ID via AJAX to a PHP function on the same page and run a query and return the result back to AJAX which would then append the final result into a div.
As I did some research, I came across this solution, but there are some shortcomings with it.
function1($_GET['id']);**//not getting the id's value**
echo "This is function 1 AND id=".$param;**//this string must be
passed back to the previous ajax request.**
AJAX request (efund.phtml)
$.ajax({
type:'GET',
url:'efund.phtml',
data:"function_to_call=0?id"+cl[3],
success: function(data){
// alert('successful');
}
});
PHP (efund.phtml)
switch ($_GET['function_to_call']) {
case 0:
function1($_GET['id']); // not getting the id's value
break;
case 1:
function2();
break;
default:
break;
}
//And your functions.
function function1($param) {
echo "This is function 1 AND id=".$param; // This string must be passed back to the previous AJAX request.
}
function function2() {
echo "This is function 2";
}
The most common way to communicate between server/client tends to be to use XML or JSON, for your case I recommend you use JSON:
$.ajax({
method: "GET",
url: "efund.phtml",
data: { function_to_call: 0, id: cl[3] }
})
.done(function( msg ) {
var obj = jQuery.parseJSON( msg );
alert( "ID obtained from server is " + obj.id );
});
And then in the server get them using:
$_GET['function_to_call'] // To obtain 'function_to_call' param
$_GET['id'] // To obtain 'id' param
To send information back as response from the server I recommend you, use the same approach and use json_encode for parse an array as JSON and return it using:
in your case for function1 it would be:
function function1($param) {
return json_encode(array ( "id" => $param ) );
}
Also, maybe you should consider if you should use GET or POST for the Http request. You can see more information about it here:
www.w3schools.com/tags/ref_httpmethods.asp
Edit:
If you have problems with the ajax request and you want to check if the ajax request is executed correctly modify the Ajax code like this:
$.ajax({
method: "GET",
url: "efund.phtml",
data: { function_to_call: 0, id: cl[3] }
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
}).done(function( msg ) {
var obj = jQuery.parseJSON( msg );
alert( "ID obtained from server is " + obj.id );
});
Change
data:"function_to_call=0?id"+cl[3],
to
data: {function_to_call: 0,id : cl[3]},
in this case data work as object and it is easy to fetch value.
According to your only first condition called every time because you are passing function_to_call=0
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'];
}
I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!