Ajax get request succeds on localhost but fails online - json

I'm try to get data via an ajax get request in Wordpress and I wrote a script in javascript and another in php to handle it.
The code for javascript is the following:
window.loadServices = function loadServices(){
var data = {
action: 'get_services',
perpage: '6',
};
$.ajax({
type: 'GET',
url: sendbooking.ajaxurl,
data: data,
dataType: 'json',
success: function (response) {
post = response.data;
console.log(response);
$.each(post, function(){
elem = $(this)[0];
media = elem._links['wp:featuredmedia']
var media_href;
$.each(media, function(){
media_href = $(this)[0].href;
})
// console.log(elem);
var image;
$.ajax({
type: 'GET',
url: media_href,
dataType: 'JSON',
success: function(data){
image = data.source_url;
},
async: false,
})
$('.services .elements .elements-container').append(
$('<div />', {
class: 'loader',
}).append(
$('<img />', {
src: '/wp-content/themes/farmhouse/assets/images/loader.gif'
})
)
)
setTimeout(function(){
$('.loader').fadeOut();
}, 2000);
$('.services .elements .elements-container').append(
$('<div />', {
class: 'element '+elem.type,
}).append(
$('<a />', {
href: elem.link
}).append(
$('<div />', {
class: 'element-image',
}).append(
$('<img />', {
src: image,
})
)
)
).append(
$('<h5 />', {
class: 'element-title',
}).append(
$('<a />', {
href: elem.link,
text: elem.title.rendered
})
)
)
)
setTimeout(function(){
$('.loader').remove();
}, 2000);
})
},
});
}
This is instead the code for php:
if(!function_exists('get_services')):
function get_services(){
$data = $_GET;
$json_feed = get_site_url() . '/wp-json/wp/v2/service?per_page='.$data['perpage'];
$json = file_get_contents($json_feed);
$json_decoded = json_decode($json);
wp_send_json_success($json_decoded);
}
add_action('wp_ajax_get_services', 'get_services');
add_action('wp_ajax_nopriv_get_services', 'get_services');
endif;
The problem I'm having is that on localhost, this works fine, I get the content I need, without any problem. When I'm going to deploy the site on line, the ajax doesn't retrieve anything. Throwing console.logs, I noticed that the scripts fail when getting data from the api url (file_get_contents), but if you go there directly via browser's address bar, or through postman, data are served correctly. (You can test: http://www.dsoftwarelab.it/ilpiastrino/wp-json/wp/v2/service?per_page=6).
I really don't know how to solve it, since I've really tried everything.

Case 1 : You don't have access rights on server.
If you have root access, edit php.ini, usually located at /etc/php.ini.
If you dont have root access, try to add ini_set('allow_url_fopen', 'On'); or ini_set('allow_url_fopen', '1');.
If you can't see php.ini, try using phpinfo() in a PHP script to find the php.ini location.
Case 2 : You have miss the SSL parameter in .
$url= 'https://example.com';
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));
Case 3 : 403 FORBIDDEN
The server responds with an "403 FORBIDDEN" status code. So file_get_contents() works fine, but the server you are trying to access (or a proxy or something in between) dont allow it.

Do not convert json to array. comment this line $json_decoded = json_decode($json);
if(!function_exists('get_services')):
function get_services(){
$data = $_GET;
$json_feed = get_site_url() . '/wp-json/wp/v2/service?per_page='.$data['perpage'];
$json = file_get_contents($json_feed);
//dont need this line
//$json_decoded = json_decode($json);
wp_send_json_success($json);
}
add_action('wp_ajax_get_services', 'get_services');
add_action('wp_ajax_nopriv_get_services', 'get_services');
endif;

Related

Posting object using ajax to PHP

I'm trying to post to php using ajax.
I can't seem to figure why the data isn't been posted.
The console.log shows 'success'.
var obj shown is for check only.
the code:
var obj = {'age':'32'};
obj = JSON.stringify(obj);
$.ajax({
type: 'post',
data: {'phpobj': obj},
dataType: 'json',
success: function(data){
//do whatever.
console.log('success');
}
});
and the php (in the same url):
if (isset($_POST['phpobj'])) {
echo 'phpobj is POSTED:</br></br>';
$php_obj = $_POST['phpobj'];
$decoded = json_decode($php_obj, true);
var_dump($decoded);
} else {
echo 'phpobj Wasnt POSTED';
}
Thanks for helpers.
Please try replacing your code like this
JQUERY
$.ajax({
type: 'post',
data: {'age': 32},
dataType: 'json',
success: function(data){
//do whatever.
console.log('success');
}
});
PHP
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo 'REQUEST is POSTED:</br></br>';
$age= $_POST['age'];
var_dump($_POST);exit;
} else {
echo 'phpobj Wasnt POSTED';
}
Change the rest according to your requirements. Thanks
i encounterd the same problem before, i gave up using ajax to post.
you can use the jquery to create a form then let the user submit it to php.

send data from twig to controller using ajax in symfony 3.4

i want to send data from a view (Twig) to controller without refreshing the page so i used ajax , in order to pass data to a specific controller action .
this is my ajax code in the twig file :
<script>
var data = {request : $('#content').val()};
$.ajax({
type: "POST",
url: "{{ path('AjoutAjax') }}",
data: data,
success: function (data, dataType) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error : ' + errorThrown);
}
});
</script>
this is my twig file :
<div class="column text-lg">Subtotal: <span class="text-medium" id="content">
this is my controller action :
public function AjoutAjaxAction(Request $request)
{
$data = $request->request->get('request');
echo $data;
$em = $this->getDoctrine()->getManager();
$reservation = $em->getRepository('techeventBundle:Panier')->find(11);
$reservation->setTotal($data);
$em->flush();
return $this->render('#reservation/Default/afficherPanier.html.twig');
}
and this is the routing file
affichage:
path: /afficherPanier/{iduser}
defaults: { _controller: reservationBundle:Default:afficherPanier }
AjoutAjax:
path: /ajoutAjax
defaults: { _controller: reservationBundle:Default:AjoutAjax }
the problem is :
1/ it's not sending data to the controller action because when i tried with the path 'AjoutAjax' it's not showing the echo '$data' .
2/with any path should i test with 'affichage' or 'AjoutAjax' to know that is working ?
'
I'm no front-end dev but but i think you should use .html() or .text() instead of .val() on a span element
https://api.jquery.com/text/#text

Check to see if something is already toggled in custom directive angularjs

I have a toggle button I've created with a custom directive for "likes". Its using a JSON field with a true/false. The field is is_liked. I've got the toggle portion set up just fine, but I'm having some trouble checking to see wether the field is true or false before adding the toggle.
I need to somehow check to see if the field is already true/false so that button can show wether its already checked or not. Right now the toggle always starts off as unchecked regardless of if the field has been checked or not. Hopefully I'm explaining this well enough. My directive looks like this..
/*jshint unused:false */
/*global _:false */
/*global $:false */
'use strict';
angular.module('hscApp')
.directive('likes' ,['$http',function ($http)
{
return {
restrict: 'A',
scope: { event: '=' },
template: '<div ng-click="togglelike()">'+
'<a ng-hide="isliked"><i class="icon-star"></i>Like</a>'+
'<a ng-show="isliked"><i class="icon-star">Unlike</i></a>'+
'</div>',
link: function($scope){
$scope.isliked = $scope.event.is_liked;
$scope.togglelike = function(){
$scope.eventid = $scope.event.id;
$scope.classes = $scope.event.class;
if ($scope.isliked){
var url = 'http://www.test.com/api/v1/user_favorites/0.json';
var del = $.param({listing_type: $scope.classes, listing_id: $scope.eventid, _method: 'delete'});
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: del
});
}
else {
var urls = 'http://www.test.com/api/v1/user_favorites.json';
var dels = $.param({listing_type: $scope.classes, listing_id: $scope.eventid});
$http({
method: 'POST',
url: urls,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: dels
});
}
$scope.isliked = !$scope.isliked;
};
}
};
}]);
So on each page load the like button will always start out as Like even if it has already been liked and should be showing Unlike. How do I check to see what state the button is currently in and apply the correct toggle action to it?
You can store a variable on the scope rather than the $scope when your directive loads
.directive('likes' ,['$http',function ($http)
{
return {
restrict: 'A',
scope: { event: '=',
isLikedLocal: "=" // can pass this in as a param, otherwise you can make it one way data bound using # instead of =
},
template: '<div ng-click="togglelike()">'+
'<a ng-hide="isLikedLocal"><i class="icon-star"></i>Like</a>'+
'<a ng-show="isLikedLocal"><i class="icon-star">Unlike</i></a>'+
'</div>',
link: function($scope){ // use function link(scope, element, attrs) instead for consistency
scope.isLikedLocal= $scope.event.is_liked;
$scope.eventid = $scope.event.id;
$scope.classes = $scope.event.class;
scope.togglelike = function(){
if (scope.isLikedLocal){
unlike();
}
else {
like();
}
scope.isLikedLocal= !scope.isLikedLocal;
}
function unLike(){
var url = 'http://www.test.com/api/v1/user_favorites/0.json';
var del = $.param({listing_type: $scope.classes, listing_id: $scope.eventid, _method: 'delete'});
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: del
});
}
function like(){
var urls = 'http://www.test.com/api/v1/user_favorites.json';
var dels = $.param({listing_type: $scope.classes, listing_id: $scope.eventid});
$http({
method: 'POST',
url: urls,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: dels
});
}
function getLike(){
//some http ajax call to get current status of button
$http.get().then(...)
scope.isLikedLocal = result from get call
}
// initializing the directive should make an ajax call, unless you are passing the data in as a parameter
getLike();
};
}
};
}]);

Data not getting saved using JQuery.ajax

I want to save data from Textbox on Button click. I am using JQuery AJAX for this task like below. Please note that I made this tags inside theme function.
function theme_user_post_block($vars)
{
$themeUserCommentInput ='';
$themeUserCommentInput .= '<textarea id="txt_1"rows="1" cols="50"></textarea>';
$themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center"
class="btnPostComment" id="btn_1" />'
return $themeUserCommentInput;
}
This able to show me Textbox and Button inside the page. Now here is my JS code:-
(function($)
{
Drupal.behaviors.PostComment= {
attach: function (context, settings) {
$('.btnPostComment', context).click(function (event) {
var post = "&newcomment=Comment1&logid=log1";
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
data: post,
success: function (data) { alert(data); },
error: function(jqXHR, textStatus, errorThrown){alert(textStatus +
errorThrown);}
});
});
}
}
})(jQuery);
Next I create a Menu Page with URL Name as follows:-
function postcomment_menu(){
$items=array();
$items['postcomment']=array(
'title'=>t(''),
'type'=> MENU_CALLBACK,
'page callback' => 'user_comment_post',
'access arguments' => array('access content'),
);
return $items;
}
function user_comment_post(){
global $user;
$cid = db_insert('user_comment')
->fields(array(
'comment_user_id' => $user->uid,
'reference_id' => $_POST['logid'],
'comment_desc'=>$_POST['newcomment'],
'createdon'=>REQUEST_TIME,
))
->execute();
if($cid!=0)
{
//GetUserComments($i);
drupal_json_output("success");
}
}
So I have done all things that is required for jQuery+Ajax Submit functionality. When I press "Post Comment" button it gives me error in alert says "errorundefined". The alert shows as a result of error inside the jQuery.AJAX function. Also the custom menu callback is also not getting called.
post the data as object...and make sure your post url is correct.. the url doesn't looks correct
var post = {newcomment: 'Comment1',logid:'log1'};
I came to end of this problem. I dont know what might be the resolution or root cause but I end up solving this problem. I meagre add one line(async: false) in my jQuery.ajax function and everything works perfectly. Please see the code below:
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
async: false,
data: post,
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + errorThrown);
}
});
If anyone have any knowledge as what this line will do then please share with us.

Post array is missing json from ajax request

I'm trying to make a dynamic document previewer. The user can input certain document header options and based on their account information it will generate a document with a dynamic header. I eventually want to preview a full pdf but I am working on just the header right now.
What I am trying to do is make a page with a form that the user can fill out, then press a button to preview the header.
$.ajaxSetup({
type: 'POST',
timeout: 10000
});
$("#preview_header").click(function(){
var full_url = //appropriate URL
var preview_data = {
"wsid": "default",
"page": "default",
"banner_area1": "default",
"banner_area2": "default",
"banner_area3": "default",
"uid": "default",
"fid": "default",
"cid": "default",
"assignment_type": "default"
};
preview_data.wsid = $("#worksheet_picker").val();
preview_data.page = $("#page_picker").val();
preview_data.banner_area1 = $("#banner_area1").val();
preview_data.banner_area2 = $("#banner_area2").val();
preview_data.banner_area3 = $("#banner_area3").val();
preview_data.uid = $("#member_uid").val();
preview_data.fid = $("#family_id").val();
preview_data.assignment_type = 'family';
preview_data.cid = $("#class_id").val();
var JSONText = JSON.stringify( preview_data );
alert('Full JSON - ' + JSONText);
$.ajax({
async: true,
url: full_url,
data: { previewInfo : JSONText }, //Passes necessary form information
dataType: 'json',
success: function(output){
var reply = output;
if ( reply.status == "success" ){
$("#preview").attr("src", reply.image );
} else {
alert('Failed to create image preview of the assignment.');
}
}
});
});
As far as I can tell, the above method is working fine. It hits the right Codeigniter page and when the ajax method is set to return a hard coded image it works just fine. The AJAX seems to be well formatted but just in case here is what it outputs when I fill out forms with the corresponding values:
Full JSON - {"wsid":"4","page":"1","banner_area1":"link1",
"banner_area2":"link2","banner_area3":"link3",
"uid":"1","fid":"1","assignment_type":"family"}
So first off, let's start with what is working in the corresponding controller method for the ajax reply:
$data = array(
'status' => 'success',
'image' => //static image link
);
$this->output->set_content_type('text/javascript;charset=UTF-8');
echo json_encode($data);
But whenever I try to modify it like so:
$preview_data = json_decode($this->input->post('previewInfo'));
//Got this one
mail('me#gmail.com', 'Start Email', 'Some email' );
//Empty email
mail('me#gmail.com', 'Dump Post', var_dump($_POST));
//Empty email
mail('me#gmail.com', 'Post data', var_dump($preview_data) );
//returns an email with 1 for body
mail('me#gmail.com', 'Post data', print_r($this->input->post()) );
//returns an email with 1 for body
mail('me#gmail.com', 'Post data',
print_r($this->input->post('previewInfo')) );
//returns an email with 1 for body
mail('me#gmail.com', 'Post data', print_r($preview_data) );
$data = array(
'status' => 'success',
'image' => //static image link
);
$this->output->set_content_type('text/javascript;charset=UTF-8');
echo json_encode($data);
The modified one doesn't return the static data either. So it would seem that the post array is not being intialized properly. Anyone see the bug?
If you want to send your Ajax request with the post method, you need to set type to POST in your $.ajax options.
Also, async is true by default, so setting it is not necessary. Additionally, you should consider using .done and .fail as opposed to success and fail, as they are slated to be deprecated very soon.
Like so:
$.ajax({
type: "POST",
url: full_url,
data: { previewInfo : JSONText }, //Passes necessary form information
dataType: 'json'
}).done(function (output, textStatus, jqXHR) {
var reply = output;
if ( reply.status == "success" ){
$("#preview").attr("src", reply.image );
} else {
alert('Failed to create image preview of the assignment.');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// now you have the XHR, text status, and error to debug with
});
There was 2 problems that lead to the solution to this problem:
1)
As Austin and Gavin said: var_dump and print_r should not be outputting to the browser.
The solution was to debug with firefox extensions / chrome.
2)
$preview_data = json_decode($this->input->post('previewInfo'));
was changed to
$preview_data = json_decode($this->input->post('previewInfo'), true);
The secondy optional parameter of json_decode is to tell the method whether you are expecting an associative object or a list of things. As it happens, I was reading in and wanted an associative array.