Laravel API working in localhost but not worked in server while Request $request - ajax

Route:
Route::get('api/get-market-list','MemberTradesController#getMarketList');
Route::get('api/get-market-list1','MemberTradesController#getMarketListtest');
Controller :
public function getMarketListtest(Request $request){
$markets = DB::table("markets")
->pluck("market","id");
return response() -> json($markets);
}
public function getMarketList(Request $request){
$markets = DB::table("markets")
->where("exchange_id", $request->exchange_id)
->pluck("market","id");
return response() -> json($markets);
}
<title>Laravel 5 - Dynamic autocomplete search using select2 JS Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script type="text/javascript">
$('#exchange').change(function(){
var exchangeID = $(this).val();
if(exchangeID){
$.ajax({
type:"GET",
url:"{{url('api/get-market-list')}}?exchange_id="+exchangeID,
success:function(res){
if(res){
$("#market").empty();
$("#market").append('<option>Select</option>');
$.each(res,function(key,value){
$("#market").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#market").empty();
}
}
});
}else{
$("#market").empty();
$("#symbol").empty();
}
});
</script>
http://www.yourtradelog.com/api/get-market-list1
below URL is not fetching data so.. my javascript are not giving me result
http://www.yourtradelog.com/api/get-market-list?exchange_id=+1 (not working)
I want to know why this is not woring on server but all are working fine in localhost
**
ERROR LOG
**: 2 2: https://i.stack.imgur.com/rnPfh.png
Composer update error
Database markets table

I just tested the link you provided and this is my take on the situation:
The parameter you're sending via url has a + before the id (....=+1)
On your route, you're not validating if exchange_id exists (you should). If you're planning on retrieving an ID, you may call it to be in the url, or create a validation in order to check if it's correct.
According to your error (on [2]), make sure the route (and error page) are accessible without login (since you're not working with the csrf_token as I can see). When I send a request, I receive an empty json array, so I can't replicate that error. You can always try composer update
Edit: Since you say it works on localhost, have you deployed it successfully on the production or just copy-pasta? Attention to your .env file and file permissions

Related

Minimum Working Example for ajax POST in Laravel 5.3

Can someone please explain the ajax post method in Laravel 5.3 with a full-working minimum example?
I know there are some resources in the web, but I miss a concise, straight-forward minimum example.
I presume you have a basic understanding of the model-controler-view paradigm, a basic understanding of Laravel and a basic understanding of JavaScript and JQuery (which I will use for reasons of simplicity).
We will create an edit field and a button which posts to the server. (This works for all versions from Laravel 5.0 to 5.6)
1. The Routes
At first you need to add routes to your routes/web.php. Create one route for the view, just as you know from ordinary views:
Route::get('ajax', function(){ return view('ajax'); });
The second route you need to create is the route that handles the ajax post request. Take notice that it is using the post method:
Route::post('/postajax','AjaxController#post');
2. The Controller Function
In the (second) route you created just now, the Controller function post in the AjaxController is called. So create the Controller
php artisan make:controller AjaxController
and in the app/Http/Controllers/AjaxController.php add the function post containing the following lines:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller {
public function post(Request $request){
$response = array(
'status' => 'success',
'msg' => $request->message,
);
return response()->json($response);
}
}
The function is ready to receive data via a Http request and returns a json-formatted response (which consists of the status 'success' and the message the function got from the request).
3. The View
In the first step we defined the route pointing to the view ajax, so now create the view ajax.blade.php.
<!DOCTYPE html>
<html>
<head>
<!-- load jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- provide the csrf token -->
<meta name="csrf-token" content="{{ csrf_token() }}" />
<script>
$(document).ready(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(".postbutton").click(function(){
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN, message:$(".getinfo").val()},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
$(".writeinfo").append(data.msg);
}
});
});
});
</script>
</head>
<body>
<input class="getinfo"></input>
<button class="postbutton">Post via ajax!</button>
<div class="writeinfo"></div>
</body>
</html>
If you wonder what's the matter with this csrf-token, read https://laravel.com/docs/5.3/csrf

Laravel: workaround the CSRF token via Ajax issue :

Scenario:
I want via ajax send chosen words to a Controller, but I am getting all the time "Internal server error" After a full Sunday of struggling and swearing I think I know why this is happening and how it could be solved. I dont have that problem if I send the word via a ordinary Form and Submit button. The issue is the mis-marriage between Ajax and the CSRF token mismatch.
So here is the Ajax snippet>
<script>
$(document).ready(function(){
$('.choose-language').on('click', function(e){
e.preventDefault();
var selectedlanguage = $(this).data('value');
alert(selectedlanguage); // it gets the value alright on clicking the paragraph
$.ajax({ // so I want to send it to the controller
type:"POST", // via post
url: 'language', // correct?
data:{'locale': selectedlanguage},
}); // HERE FINISHES THE $.POST STUFF
}); //HERE FINISHES THE CLICK FUNCTION
}); // HERE FINISHES THE DOCUMENT AND READY STUFF
</script>
Here is the HTML
<div class="choose-language">
<p class="choose-language" id="english" data-value="en" >English</p>
<p class="choose-language" id="spanish" data-value="es" >Spanish</p>
</div>
Here is the Routes:
Route::get('/', function () {
return view('welcome');
});
Route::post('language', array(
'as' =>'language',
'uses' => 'LanguageController#changelanguage'
));
And the Controller
class LanguageController extends Controller
{
public function changelanguage()
{
Session::set('locale', \Input::get('locale'));
return \Redirect::back();
}
}
So, if I go to Middleware, I can see there is a File called VerifyCSRFToken.php and inside that file there is this:
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
// code here
];
}
So, I am sure that should fix it, but I wrote 'language' where the // code here is and did not make any difference. There must be other bugs..
Thanks a lot.
UPDATE:
I have found a typo (apologies I had written redirecto instead of redirect) and I m not getting errors anymore.
Add the CSRF token to your HTML head:
<meta name="csrf-token" content="<?= csrf_token() ?>">
Add this to your JS file:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
The CSRF should now pass the middleware
There was one annoying thing in this HMTL code: as you see the class "choose-language" was repeated also in the div, which caused the click to be repeated twice, and the second time without actually sending a value. So I have left it there for you to see, but you do need to remove it. Once you remove it from the div, the code works correctly. So this responds and solves the issue of Ajax and Laravel CSRF. I have tested the output of the controller and it gets the word sent. Before Laravel 5.0 you had to go through a lot of hacking in the code and fix the bugs and add also conditionals in the filter to let decide when CSRF was or not coming from an Ajax, besides having to add code in every header of every page where you had Ajax sending something etc.
Now, in Laravel 5.0 you just do as I wrote in the code and you are done.

ExtJs 5.0.1: Synchronus Ajax request in Firefox

In the project we have a config singleton object, which holds configuration fetched from the server (ServerConfig). It is defined like
Ext.define('SI.ServerConfig', {
singleton: true,
constructor: function () {
this.callParent(arguments);
// Closure which holds the serverConfig after the synchronus request
var serverConfig;
Ext.Ajax.request({
url: 'example.de/getConfig.php',
method: 'POST',
async: false,
success: function(response){
var responseObj = Ext.JSON.decode(response.responseText);
serverConfig = responseObj.serverConfig;
}
});
//definition of setter/getter function for the serverConfig closure
this.get = function (optionName, defaultVal) {
if (Ext.isDefined(serverConfig[optionName])){
return serverConfig[optionName];
}
return defaultVal;
};
this.set = function (optionName, value) {
serverConfig[optionName] = value;
};
}
});
In the constructor we have a closure which holds after the synchrone Ajax request the server config object.
We need to make a synchrone request, because the server config values are needed in various other classes to provide config bevore creation.
With a setter and a getter function we provide access to the values defined in it.In every controller/view/model we need access to the server config, we require the singleton.
Ext.define('SI.view.TestView', {
extends: 'Ext.panel.Panel',
requires: ['SI.ServerConfig'],
// This fails most of the time in Firefox, but works every time in Chrome and IE 8+
title: SI.ServerConfig.get('testTitle')
});
But when we access the singleton in the config object in class definition, the server config singleton is not instantiated in Firefox all the time. In Chrome and in Internet Explorer 8+ it is working as expected.
So to be shure we have the singleton ready to use we tried the following. We moved the Application definition in the callback of an Ext.require. But this does not fix it for Firefox.
Ext.require([
'SI.ServerConfig'
], function () {
Ext.define('SI.Application', {
// ....
}); /
});
In the Firefox Debugger the following is logged:
Synchrone XMLHttpRequests am Haupt-Thread sollte nicht mehr verwendet werden,
weil es nachteilige Effekte für das Erlebnis der Endbenutzer hat.
Für weitere Hilfe siehe http://xhr.spec.whatwg.org/
From the XHR spezification:
Synchronous XMLHttpRequest outside of workers is in the process of being
removed from the web platform as it has detrimental effects to the end
user's experience. (This is a long process that takes many years.)
Developers must not pass false for the async argument when the JavaScript
global environment is a document environment. User agents are strongly
encouraged to warn about such usage in developer tools and may experiment with
throwing anInvalidAccessError exception when it occurs.
So synchrone requests will be removed in the future and only allowed in webworkers.
We need a solution for this.
The problem only occurs in developer mode, when we build it with sencha app build, it works in Firefox...
Thanks for any suggestions.
And-y
Update index.html -> index.php
I changed index.html into index.php like #colinramsay suggested and included the server config object before microloader is included.
Now the warning about Synchrone XMLHttpRequests is gone in Firefox.
But the problem when accessing the singleton in the config object in class definition still remains for the Firefox.
Another totally different approach is to change your application's root index.html to an index.php that does something like the following:
<!DOCTYPE HTML>
<html manifest="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var SI = {};
<?php
echo 'SI.ServerConfig = { "testTitle": "some string" }';
?>
</script>
<!-- The line below must be kept intact for Sencha Cmd to build your application -->
<script id="microloader" type="text/javascript" src="bootstrap.js"></script>
</head>
<body></body>
</html>
This allows you to change your get code to something like:
function get(optionName, defaultVal) {
if (Ext.isDefined(SI.ServerConfig[optionName])){
return SI.ServerConfig[optionName];
}
return defaultVal;
}
You are using PHP to directly output your configuration to the HTML page as JSON before Ext JS and your application load.
Try this:
Ext.define('SI.view.TestView', {
extends: 'Ext.panel.Panel',
requires: ['SI.ServerConfig'],
constructor: function() {
this.callParent();
this.setTitle(SI.ServerConfig.get('testTitle'));
}
});
I suspect this is a load order issue. In your original code, Ext.define would run at the same time SI.ServerConfig, before the requires kicks in, so SI.ServerConfig might not have loaded via requires. By calling it in the constructor you can be sure that all of the requires have been fulfilled and so it should be available.

Simple AJAX query with CodeIgniter and jQuery

I'm simply trying to pull a div from a page called "Load-about.php" to my main page with AJAX.
I've been following tutsnet courses "30 Days to learn jQuery" but I'm stuck when it is about to load a content from another page since I'm using CI and I'm trying to adapt those courses.
So I have my main page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Load</title>
<link rel="stylesheet" href="<?php echo base_url('bootstrap/css/bootstrap.min.css'); ?>" >
<style>
</style>
</head>
<body>
Try to make AJAX working !
</br>
Contact
<div class="wrap"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
(function() {
var wrap = $('div.wrap');
$('a').on('click', function(e) {
var href = $(this).attr('href');
wrap.load(href +'.container' ) ;
e.preventDefault();
});
})();
</script>
</body>
</html>
I'm simply calling a very simple CI Controller that only call the asked view
And Everything was working fine when working without the links.
But now, I am redirected to the page instead of using the AJAX call. Why ? Why does
e.preventDefault();
or
return false;
isn't preventing the links to their default action ?
Thanks
EDIT: Thanks to Jai, I found my error, a simple coma.
But, now, I'm getting "GET http://www.localhost.com/CodeIgniterJQUERY/index.php/Ajax/lessonTwentyThree/Load-Contact.container 500 (Internal Server Error) "
the problem comes from the .container as I wanted to specify the class and Ci understand it as it is a parameter.
Here is the Controller :
class Ajax extends CI_Controller {
/**
* Nous allons ici nous occuper de toutes les fcts AJAX
*/
public function lessonTwentyThree($page)
{ // En fait, on a pas besoin de ca, on va directement loader la vue directement.
$this->load->view($page);
}
}
I just want to grab a div from Load-Contact to the main page.
In addition to what Jai said. you have a codeigniter logical error.
when you say:
$this->load->view($page);
it means that codeigniter will redirect internally to the view. In your case what you need is to get back the view content and not to load it.
So, codeigniter support a third parameter with function view() that asks it to get the view content as String. you can do that and send the view to be loaded like this:
$string = $this->load->view($page, '', true);
echo $string;
Hope this will solve your problem
You have to move it up:
(function($) {
var wrap = $('div.wrap');
$('a').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href');
wrap.load(href +'.container' ) ;
});
})(jQuery);
and you have to put a ',' after click handler.
also try to change
(function() {
})();
to
$(function() {
});

ajaxComplete/ajaxStop/ajaxSuccess not firing

I appreciate any and all help. I am a beginner with little jQuery/AJAX experience and I have been going crazy trying to figure out why I can't figure this out.
I'm writing a Facebook page application that has the user grant permissions and upload a video to the page. All of this works fine and dandy. This is not so much a Facebook API related issue as it is an ajax issue (at least I think).
Basically, I am trying to gain control of the page IN SOME WAY after the user uploads a video. I am using the [malsup jQuery Form Plugin][1] to have the resulting page (which is a page on Facebook displaying returned JSON values) load in a hidden iframe.
I am able to get ajaxStart to fire, and I've tested this by having it change the background color or print an alert message when I click "Upload". However, when the upload completes (and it does complete successfully), NOTHING ELSE HAPPENS. The returned JSON values load in the hidden iframe and the page sits there. I have tried getting ajaxComplete, ajaxStop and ajaxSuccess to fire, but none of them do for whatever reason.
So overall, here is what I am trying to accomplish:
- I want to redirect the user or make some hidden content appear after the file upload completes. I don't even care if there's errors. I just need SOMETHING to happen.
- I am using the jQuery Form Plugin because I am not unfortunately not advanced enough to figure out how to use that value and do something with it, but if anyone can steer me in the right direction, that would be appreciated.
And finally, here is my code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
iframeTarget: '#output2',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('#theform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
</script>
<script type="text/javascript">
jQuery().ready(function(){
$('body').ajaxStart(function() {
$(this).css("background-color","red");
});
$('body').ajaxSend(function() {
$(this).css("background-color","blue");
});
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
$('body').ajaxStop(function() {
$(this).css("background-color","purple");
});
});
</script>
</head>
<body>
<?php
$app_id = "xxxxxxx";
$app_secret = "xxxxx";
$my_url = "xxxxxx";
$video_title = "xxxxxxxxx";
$video_desc = "xxxxxxxxx";
$page_id = "xxxxxxxx";
$code = $_REQUEST["code"];
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&display=popup&scope=email,publish_stream,manage_pages";
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($current_url != $dialog_url)
{
echo('<script>window.location ="' . $dialog_url . '";</script>');
}
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&access_token=". $access_token;
// Create a simple form
echo '<form action=" '.$post_url.' " method="POST" enctype="multipart/form-data" id="theform">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" id="button-upload" />';
echo '</form>';
}
?>
<iframe id="output2" name="output2"></iframe>
</body></html>
Thank you for your help!!
It seams you are getting an Ajax Error. I don't see any error handler in your code. Could you try to add an error handler as follows
<script>
$(document).ready(function(){
$(document).ajaxError(function(e, jqxhr, settings, exception) {
alert(exception);
})
})
</script>
I have played around with file uploads, and there are a complicated beast because of all the security that browsers have for protecting users file systems and whatnot.
On to your problem, I think that there is a good chance that your AjaxForm jQuery plugin doesn't connect properly to the global Ajax state for Jquery. Even if it did, I would say that tapping into the global Ajax state is a bad design. If you add any other ajax requests to this page, then your ajaxComplete, ajaxStop, etc. functions are going to start getting called.
Your better approach is to use the callbacks provided by the AjaxForm plugin. Lets focus on this first part of your code.
Does this work?
success: showResponse // post-submit callback
...
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
If so, could you replace this:
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
With this:
function showResponse(responseText, statusText, xhr, $form) {
$(this).css("background-color","green");
}
I believe that using the success: callback is the intended use of the AjaxForm plugin.
The jquery ajaxSend or ajaxStart throws some kind of an error and the document does not execute ajaxComplete. I tried to fix the bug for quite a while and was only able to find a workaround:
function hideAjaxIndicator() {
$('#ajax-indicator').hide();
}
$(document).ready(function () {
setTimeout(hideAjaxIndicator, 1000);
});
You can add this to .js file.

Resources