Proper way of sending json response - ajax

I used to write in the controller method:
echo json_encode(TRUE);die;
to pass the success message to the AJAX so that.
e.g.
if($user->save())
{
echo json_encode(TRUE);die;
}
and in ajax:
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('user added!');
}
But then i saw most using:
return Response::json(TRUE); die; instead of echo json_encode(TRUE);die; what is the difference between these two? Or is it exact similar to echo vs return?

If you just echo text, your response will be sent back the the content type of plain/html.
If you return response()->json(), then your response will be sent back with the content type of application/json.
Some clients may not care one way or another, but others may behave differently if the headers say the response is json. In either case, the application/json response is more semantically correct.

I recomend you to echo the result of a function. For example:
function save(){
//magic happens here
return $result; //can be false or true (for example)
}
and in the file which is called in the ajax request simply put:
echo json_encode(save());
finally you can compare the result in the client side:
success: function(response){
var result = $.parseJSON(response);
if(result) alert("Success!");
else alert("Sorry try later");
}

This is how I have done and it's very standard. I have create one helpers.php file and put it in composer.json so no need to further include it in application.
composer.json
"autoload": {
"files": [
"app/Utils/helper.php"
]
}
run command
composer dumpautoload.
Create method for success response in helpers.php
function success($data, $message, $status = 200, $headers = [])
{
$result = [];
$result['flag'] = true;
$result['message'] = $message;
$result['data'] = $data;
return response()->json($result, $status, $headers);
}
sending success message from controller.
return success($user, 'User logged in successfully.');
Create method for error response in helpers.php
function error($code, $message, $status = 200, $errors = [], $headers = [])
{
$error = [];
$error['flag'] = false;
$error['message'] = $message;
$error['code'] = $code;
if (!empty($errors))
{
$error['errors'] = $errors;
}
return response()->json($error, $status, $headers);
}
sending error message from controller.
return error(401, 'These credentials do not match our records.',401);

Related

Laravel: return data from server without redirect

What I'm trying to do is call function form server and validate data in javascript function but the return statement from server make redirect before response.complete("success")
button.onclick = async function handlePurchase() {
const payment = new PaymentRequest(methods, details, options);
try {
const response = await payment.show();
// Call server logic here and validate response if OK continue
// But server response redirect here so code not completed
$('#checkout-form').submit();
$.ajax({
url: '{{route("apple-pay")}}',
type: 'post',
data: $('#checkout-form').serialize(),
success: function(data){
console.log('data :>> ', data);
}
});
await response.complete("success");
// redirect to success page
} catch (err) {
console.error("Uh oh, something bad happened", err.message);
}
}
Server function:
public function pay(Request $request)
{
$merchant_id = env('CREDIMAX_MERCHANT_ID');
$password = env('CREDIMAX_INTEGRATION_PASSWORD');
$response = Http::withBasicAuth('merchant.'.$merchant_id, $password)->put
('https://example.com/api/rest/merchant/'.$merchant_id.'/order/1530/transaction/1', $data);
return $respone->json();
}
Seperate the request you are making to the third party app and the response you are sending back to you ajax call. This is how I mean:
public function pay(Request $request)
{
$merchant_id = env('CREDIMAX_MERCHANT_ID');
$password = env('CREDIMAX_INTEGRATION_PASSWORD');
$response = Http::withBasicAuth('merchant.'.$merchant_id, $password)->put
('https://example.com/api/rest/merchant/'.$merchant_id.'/order/1530/transaction/1', $data);
return response()->json([
'success' => $response->ok() ? 1 : 0,
...
]);
}
Check the last line in the controller it says "return $respone->json();" and should be "return $response->json();" -- missing the "s" in response.

Make an Ajax request in Symfony2

My problem is that the method doesn't return a true result.
I want to test if the email of input exists in my entity or not.
Here is the controller:
public function verificationAction(Request $request)
{
if ($this->container->get('request')->isXmlHttpRequest()) {
$email=$request->request->get('email');
$em=$this->getDoctrine()->getEntityManager();
$resp= $em->getRepository("CMSiteBundle:Prospect")->findBy(array('email'=>$email));
$response =new Response(json_encode($resp));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
You could try an old-trick. Since in Symfony Controller Actions, You must return a Response why not fake a DEAD RESPONSE like so:
<?php
class ABCController {
public function verificationAction(Request $request) {
if ($this->container->get('request')->isXmlHttpRequest()) {
$email = $request->request->get('email');
$em = $this->getDoctrine()->getEntityManager();
$resp = $em->getRepository("CMSiteBundle:Prospect")
->findBy(array('email' => $email));
//$response = new Response(json_encode($resp));
//$response->headers->set('Content-Type', 'application/json');
// THE TRICK IS THAT DIE RUNS FIRST
// THUS SENDS YOUR RESPONSE YOU THEREBY
// STOPPING THE RETURN FROM FIRING... ;-)
return die(json_encode($resp));
}
}
}
Perhaps this very Old Trick still works for you... ;-)

Ajax response printing whole php code written in php file, What to do?

This is my http get code, here console.log(data) is printing whole php code instead of echoed statement. Kindly help me guys i am not able to figure out whats happening. I am making an ionic angular app.
Angular Code
// define angular module/app
var formApp = angular.module('formApp', [])
// create angular controller and pass in $scope and $http
.controller('formController', function ($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};
// process the form
$scope.processForm = function() {
$http({
method : 'GET',
url : 'process.php',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorSuperhero = data.errors.superheroAlias;
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
});
PHP Code
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['superheroAlias']))
$errors['superheroAlias'] = 'Superhero alias is required.';
// return a response ===========================================================
// response if there are errors
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
Console Output/Ajax Response
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['superheroAlias']))
$errors['superheroAlias'] = 'Superhero alias is required.';
// return a response ===========================================================
// response if there are errors
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
As you can see it is sending the whole php code instead of echoed statement.
I know this thread is old, but try to check your .htaccess file, if you have written down a rule like:
Use PHP5.4 as default
AddHandler application/x-httpd-php54 .php
Get rid of it. I made this mistake.

Unable to get_the_content(); of a post in Wordpress via AJAX

I'm trying to ajaxify my Wordpress theme and I use the ajax-in-WordPress method and I'm now trying get_the_content of post via functions.php. Using jQuery, when I do alert(data) I get the 'title' echo but not the content of the existing post I want (returns 0).
What am I doing wrong?
The jQuery part
$('.ajaxed,.ajaxed a,.menu-item-home a,.menu-item-object-page a').live('click', function(event) {
event.preventDefault();
var link = $(this).attr('href');
var toRemove = MySettings.url;
var rewritepath = link.replace(toRemove,'');
var handler = function(data) {
$('title').html($('title', data).html());
$('#primary').html($('#primary', data).html());
$('#primary').hide().fadeIn('slow');
$.address.title(/>([^<]*)<\/title/.exec(data)[1]);
};
$.post(ajax_object.ajaxurl, {
action: 'ajax_action',
post_id: $(this).find('input.post_id').attr('value')
},function(data) {
alert(data.post_title);
alert(data.post_content);
});
/*$.ajax({
url: link,
error: function(XMLHttpRequest, textStatus, errorThrown) {
handler(XMLHttpRequest.responseText);
},
success: function(data, textStatus, XMLHttpRequest) {
handler(data, function(){
});
}
});*/
$.address.state(MySettings.path).crawlable(true).value(rewritepath);
return false;
});
The functions.php part
<?php
function javascripts() {
if( !is_admin()){
$blogurl = get_bloginfo('url');
$thumbnail_width = get_option('thumbnail_size_w');
$thumbnail_height = get_option('thumbnail_size_h');
$path = parse_url(get_bloginfo('siteurl'), PHP_URL_PATH);
$url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js';
wp_deregister_script('jquery');
if (get_transient('google_jquery') == true) {
wp_register_script('jquery', $url, array(), null, true);
}
else {
$resp = wp_remote_head($url);
if (!is_wp_error($resp) && 200 == $resp['response']['code']) {
set_transient('google_jquery', true, 60 * 5);
wp_register_script('jquery', $url, array(), null, true);
}
else {
set_transient('google_jquery', false, 60 * 5);
$url = get_bloginfo('wpurl') . '/wp-includes/js/jquery/jquery.js';
wp_register_script('jquery', $url, array(), '1.7', true);
}
}
wp_enqueue_script('plugins.js', get_bloginfo('template_directory') . "/js/plugins.js" , array('jquery'));
wp_enqueue_script('ajax-script', get_bloginfo('template_directory') . "/js/scripts.js", array('jquery'));
wp_localize_script('ajax-script', 'ajax_object', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_localize_script('jquery', 'MySettings', array('width' => $thumbnail_width,'height' => $thumbnail_height,'url' => $blogurl,'path' => $path));
}
}
add_action('wp_enqueue_scripts', 'javascripts');
add_action('wp_ajax_ajax_action', 'ajax_action_stuff'); // ajax for logged in users
add_action('wp_ajax_nopriv_ajax_action', 'ajax_action_stuff'); // ajax for not logged in users
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
echo json_encode($post_data);
}
?>
What am I doing wrong? Thanks
Without seeing the entire scope of your code, it appears that you might be calling get_the_content() outside of the context of The Loop. If so, the function doesn't understand which post you'd like to retrieve the content for. Try organizing the function this way:
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
$title = $post_data->post_title;
$content = $post_data->post_content;
echo $title;
echo $content;
}
Here we've used get_post() to return an object with all of the post data.
The jQuery function you've created...
function(data) {
alert(data);
});
... should essentially contain a string in the data object that contains your title and content.
Here's a recommendation though, on how you can return your data in a more organized fashion, if you like.
The 'data' object (which is what you've echoed in the php function ajax_action_stuff()) is just a string value. The problem though is that the data isn't really structured in a way for jQuery to fully understand and use to its full potential. If you change your php function to return a JSON object though, then you can use all your properties in jQuery individually. I'll show you how...
function ajax_action_stuff() {
$post_id = $_POST['post_id'];
update_post_meta($post_id, 'post_key', 'meta_value'); //not sure why you need this
$post_data = get_post($post_id);
echo json_encode($post_data);
}
Then in the jQuery function you have access to each property like this:
$.post(ajax_object.ajaxurl, {
action: 'ajax_action',
post_id: $(this).find('input.post_id').attr('value')
},function(data) {
alert(data.post_title);
alert(data.post_content);
});
Have a look at the get_post() function to see all of the properties that you have available to you.
You aren't telling get_the_content() which post to retrieve the content for. Internally, this function checks for the global $post object and filters the content of that object.
So change your ajax function to something like this:
function ajax_action_stuff() {
global $post;
$post_id = $_POST[ 'post_id' ];
update_post_meta( $post_id, 'post_key', 'meta_value' );
$post = get_post( $post_id );
$title = 'title';
$content = get_the_content();
echo $title;
echo $content;
}
This will use the ID you've passed in to query the database for a specific post and populate the global $post object. Now, get_the_content() and even get_the_title() should function normally.

Routing is not working in laravel5 when call made from ajax to controller

I'm calling the jquery function on click event in signin page. From there I'm calling the $ajax function. This $ajax function should call the controller and process the function and return back with response. I have connected it using the routes.php. While running the application I'm getting error that "Requested page not found 404 error". I think there is some problem with routing. Somebody help me out to solve this issue. Thanks in advance.
The routes.php is as follows
Route::post('signin', 'LoginController#signin');
Jquery function on click event is in login_register.js file
$("#form-login").on("submit",function(e){
e.preventDefault();
var log_password = "";
var log_name = $("#log_username").val();
var password = $("#log_password").val();
if(password.trim() !== "")
{
log_password = md5(password);
}
$(".loginmessage").html('');
$(".login").attr("disabled",true);
$("#spin_signin").addClass('show');
var req = new Request();
req.data =
{
"email":log_name,
"userpassword":log_password
};
req.url = "signin";
RequestHandler(req,processlogin);
});
The ajax call made is in jquery.ajax.js file. I have given type as POST and datatype as JSON
function RequestHandler(request,response,resdata){
$=jQuery.noConflict();
var domain = "http://localhost/laravel_login/public/";
var tempurl = domain+request.url;
if(request.isfulluri){
tempurl = request.url;
}
$.ajax({
type: request.type,
url: tempurl,
data: request.data,
datatype:request.datatype,
success: function(data){
if(resdata != null && resdata != '')
response(data,resdata);
else
response(data);
},
error: function(err){
if(err.responseText == null || err.responseText == ""){
alert("Error: Check your internet connection");
}
else{
alert("Error:"+err.responseText);
}
}
});
My controller class(LoginController.php) contains
public function signin(){
$response = array();
$useremail = $this->input->post('email');
$userpassword = $this->input->post('userpassword');
if($useremail == '' || $userpassword == ''){
$response['iserror'] = TRUE;
$response['message'] = 'Please fill all the fields';
echo json_encode($response);
return;
}
else{
$result = $this->UserAuthenticate->loginUser($useremail,$userpassword);
echo json_encode($result);
return;
}
}
Please make sure that you have a route defined for your full path:
laravel_login/public/signin
You can use php artisan route:list --path=signin to see if your route is registered.
Also, in your controller method, instead of
echo json_encode($result);
return;
i would use
return response()->json($result);
as this will automatically set the proper HTTP headers for you. This way, the variable passed to your javascript callback function will be a Javascript object, without requiring additional parsing.

Resources