I'm trying to find a tricky error that I'm experiencing with react-router. For some reason, setting the state of one of my child components in a top-level page route causes the following error:
Uncaught Error: Invariant Violation: Missing "userId" parameter for path "/user/:userId"
This error happens regardless of whether or not I am navigating to that path. My routes look this:
var routes = (
<Routes>
<DefaultRoute handler={LoginPage} />
<Route name="login" handler={LoginPage} />
<Route name="home" handler={HomePage} />
<Route name="category" path="/category/:category" handler={CategoriesPage}/>
<Route name="profile" path="/user/:userId" handler={ProfilePage}/>
</Routes>
);
And my ajax call looks like this:
var Feed = React.createClass({
getInitialState: function() {
return { feedItems: [] };
},
componentDidMount: function() {
$.ajax({
url: '/api/transactions',
dataType: 'json',
success: function(transactions) {
this.setState({ feedItems: transactions });
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
....
This Feed is generated on a bunch of pages, including the HomePage and the ProfilePage. I'm having a lot of trouble figuring out how the :userId parameter could be related to the Ajax call in the feed, but that's where the stack trace leads me. Any help with what is going on here would be much appreciated.
UPDATE: Found the problem. My mongo database was out of date (model schemas changed), which was causing a host of problems, bubbling up to this Invariant Violation. I'm still not entirely sure how the two were related, but deleting old objects fixed the problem.
Thanks, #ritmatter for solving this yourself !
Just as a reference, here the answer with a link to the docs.
Remember in all your react-router <Link> elements you have in your code, to include the params object for links pointing to a parameterized route:
<Link to="BillingInfo" params={userId:"user876718236"}>Your Billing Information</Link>
<!-- linking to /user876718236/billing-info -->
Have a look here for details: react-router/Link
UPDATE [2015-03-29] corrected JSX param braces. Thanks to #Akay.
UPDATE: v1.0 (November 2015)
Named paths are no longer supported, you link to full paths. String templates in ES6 are handy for this:
// v0.13.x
<Link to="user" params={{userId: user.id}}>Mateusz</Link>
// v1.0
<Link to={`/users/${user.id}`}>Mateusz</Link>
From Changelog: Links.
Related
I am presently developing a web application with jQuery mobile. However, I found that when a "changePage" fails, I can no longer send ajax requests. After the failure, all ajax requests return an error. Here's the code executed when the submit button on the form is clicked (it's a basic user login screen):
// Event when user click the Submit login button
$('#submitLogin').on("click", function () {
// submit the user credentials to the server
$.ajax({
type: "POST",
url: "./LogUser",
data: {
EmployeeID: $('#EmployeeID').val(),
EmployeePIN: $('#EmployeePIN').val()
},
dataType: "text",
async: true,
cache: false,
error: function (rqst, text, thrownError) {
$('#dlg-login-error-message').text(thrownError);
$('#dlg-login-error-popup').popup("open");
},
success: function (data) {
if (data == "Success") {
$.mobile.changePage("./LoadScreen/Menu");
}
else {
$('#dlg-login-error-message').text(data);
$('#dlg-login-error-popup').popup("open");
}
}
});
return false;
});
If the post itself fails, I can resubmit without problem. If the .mobile.changePage fails, a "page not found" is displayed, but I am not able to resubmit, ajax no longer making request to the server and jumping directly to the error callback with a "not found" error.
I am guessing the problem comes from the fact that jQuery mobile uses AJAX request to load pages, and that somehow, ajax calls are getting mixed up somewhere.
I did more tests, even intercepted the pageloadfailed event, but nothing works. After the page change failure, AJAX calls no longer sends anything to the server and jump automatically to the error callback function.
I tried with async=false, same problem. I tried debugging jQuery-mobile, but I am still not able to find the "changePage" function itself ( the .code is quite confusing ).
I just spent the last two days trying to figure out a way to resolve this and I am seriously thinking of using something else than jQuery-mobile for our development.
I have found a workaround for my problem, but I do not know the full impact of this solution yet.
To prevent the problem, I had to set the "pushStateEnabled" configuration option to "false".
So if you find yourself with the same problem, try putting the following in a script right before the loading of the "jQuery-mobile" script.
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
Example:
<!-- Load the script for jQuery -->
<script src="~/Scripts/jquery-2.1.4.js"></script>
<!-- Set default for jQuery-Mobile, before it is actually loaded -->
<script>
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
</script>
<!-- Load the script for jQuery-Mobile -->
<script src="~/Scripts/jquery.mobile-1.4.5.js"></script>
I'm new to Laravel. I'm trying to make an AJAX request in my laravel app but I'm getting a 500 (Internal Server Error).
So, here is my request in the .blade file:
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getRequest').on('click', function () {
$.get('getMessages', function (data) {
$('#target').append(data);
});
});
});
</script>
I added the .ajaxSetup to make sure tokens are not the reason for this problem. So I typed in this .blade file also the following tag:
<meta name="csrf-token" content="{{ csrf_token() }}" />
Here is my route.php file:
Route::get('getMessages', 'PagesController#getMessages');
And here is my controller with the method in cause:
public function getMessages()
{
return "OK";
}
The problem is tricky to me, because I know that I can create a anonimous function in my route.php file for this URI and it's gonna be the same thing. Or not. I don't know because if I actually do this
Route::get('getMessages', function ()
{
return "OK";
});
instead of pointing to a method of a controller, it works! But I need it to work in a controller.
My controller is functioning properly when it comes to other methods and the name of the method is spelled correctly everywhere.
I'm working with XAMPP on Windows. I set XAMPP to work only with the current Laravel app, so when I type in "localhost" in my browser, it gets me to my app page and all of database data fetching work properly.
You should probably set your ENV to local so you can debug your code.
Maybe a faster solution for you would be for you to check the storage/logs/laravel.log and see the last stack trace so you can determine exactly where the error is coming from.
I'm comfortable working with $.ajax and also in using cache.manifest. Recently I decided to start using "get" instead of "post" to help see the parameters easier.
In this proof-of-concept, if I delete the cache.manifest from the server, everything works. But when I put the cache.manifest on the server, the page stops working with an undefined jqXHR.responseText.
Furthermore, if I change the get to a post, it works with the cache.manifest.
Q: Does an https require a post, making "get" invalid if you are using a cache manifest? It seems to be working if the cache manifest is missing and it works with the cache manifest if I use post.
var local = {}
local.type = 'get'
local.dataType = 'text'
local.data = {}
local.data.CtrlName = 'testing123'
var promise = $.ajax('where_ctrlName.cfm',local)
promise.done(done)
promise.fail(fail)
function done(response) {
console.log(response)
}
function fail(jqXHR, textStatus, errorThrown) {
debugger
}
window.applicationCache.addEventListener('updateready', updateReady, false)
function updateReady() {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
$('body').html('<h1>Updating</h1>')
setTimeout(reloadCache,1000)
}
}
function reloadCache() {
window.location.reload()
}
<html manifest="cache.manifest">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>
Here's my cache.manifest:
CACHE MANIFEST
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js
For What It's Worth, this is an https call.
I had basic SignalR functionality implemented and working in my MVC5/AngularJS application recently, but after shelfing and unshelfing the changes I am now getting an error when the connection is negotiated in $.connection.hub.start().
I've stripped down the code to the very basics, but still get this error. Poking around in the jquery.signalR-2.2.0.js where the negotiate request is made, I found that the result returned from the ajax request to http://localhost:44379/signalr/negotiate?clientProtocol=1.5&connectionData=[] is returning the HTML of the page instead of JSON data!
connection._.negotiateRequest = /* This is on line 659 */ signalR.transports._logic.ajax(connection, {
url: url, // http://localhost:44379/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D
error: function (error, statusText) {
// Irrelevant code removed.
},
success: function (result) { // We get here at least...
var res,
keepAliveData,
protocolError,
transports = [],
supportedTransports = [];
try {
res = connection._parseResponse(result); // This fails because result contains HTML.
} catch (error) {
// error.message is "Unexpected token <"
onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);
return;
}
Here is my javascript for establishing the hub/connection:
$(function () {
var hub = $.connection.testHub;
if (hub)
console.log("SignalR hub initialized.");
$.connection.hub.start().done(function () {
console.log("SignalR connection established.");
}).fail(function (err) {
console.log("Error starting SignalR connection: " + err); // Ends up here.
});
});
And the script references (I have the signalr code in a separate js file named messaging.js):
<script src="~/assets/js/signalr/jquery.signalR-2.2.0.js"></script>
<script src="~/Scripts/messaging/messaging.js"></script>
<script src="~/signalr/hubs"></script>
I don't really understand why the ajax response from signalr/negotiate would be returning HTML instead of JSON. I've stripped down the server side hub code to an empty class with [AllowAnonymous] to ensure nothing in there was causing the problem. I have the app.MapSignalR() call in Startup.cs in place. My first thought, since this occurred after shelfing and unshelfing, was that something didn't make it into the shelf and was lost, but I can't seem to find anything missing...
Anyone have any ideas?
I found the problem while playing with the rules in web.config.
Previously, I had this rule for signalr:
<add input="{REQUEST_URI}" matchType="Pattern" pattern="/signalr/hubs" negate="true" />
Changing the pattern allowed communication with /signalr/negotiate, I think:
<add input="{REQUEST_URI}" matchType="Pattern" pattern="^/(signalr)" negate="true"/>
...I have no idea how this worked before.
In creating a iphone web app, i used magento XML RPCto call magento web services. With the help of jQuery XML RPC i can access the magento web services.My code,
<script src="js/jquery.mobile-1.2.0.min.js"></script>
<script src="js/jquery-1.8.3.min.js"></script>
<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css"></link>
<script src="js/jquery.xmlrpc.js"></script>
<script>
$(function(){
$("button").click(function(){
$.xmlrpc({
url:"link of my magento/xmlrpc",
methodName:'login',
params:['user','pass'],
success: function(response, status, jqXHR) {
var res=response;
alert(res); // getting alert as session id as login response
$.xmlrpc({
url:"link of my magento/xmlrpc",
methodName:'call',
//passing session id from the previous response
params:{sessionId:res,methodName:'customer.info',customerId:'3'},
success: function(response1, status1, jqXHR1) {alert("success:"+response1);},
error: function(jqXHR1, status1, error1) {alert(error1); }
});
},
error: function(jqXHR, status, error) {alert(error); }
});
});
});
</script>
Here my problem is, when i run the app i get the session id and pass the id to next method "call" with the parameters.This code while executing gives me an error stating "Error: Calling parameters do not match signature"
I changed the way of passing parameters too but no hope. Can anyone suggest me how to solve this problem.
I believe this is a bug.
Take a look at this thread: Calling parameters do not match signature